网站搜索

javascript - 我如何将 JSX 导入到 .tsx 文件中(不是在 React 中)?


我没有使用 React。我正在使用Stenciljs。

我有以下 .tsx 文件:

export class MyComponent {
  @Prop() message: string;

  render() {
    return (<div>{this.message}</div>);
  }
}

我想改为做这个:

import myTemplate from '../my-template.??';

export class MyComponent {
  @Prop() message: string;

  render() {
    return (myTemplate);
  }
}

包含 ../my-template.?? 的内容如下:

<div>{this.message}</div>

这是可能的吗,如何实现?提前感谢任何帮助 :)

答案#1

是的,你完全可以这样做,只是有几件事你需要理清楚:

主文件

import { Template } from '../template'; // No need for file extension but we're using a named export so we need the curly braces around 'Template'

export class MyComponent {
  @Prop() message: string;

  render() {
    return ( // You don't technically need the parentheses here as you're just returning one thing
      <Template /> // When outputting an imported component, it goes in angle brackets and the backslash closes it like an HTML element
    )
  }
}

模板

import React from 'react';  // template needs React

export const Template = () => { // defining the export in this way is known as a named export
  return (
    <p>A message here</p>
  )
}

好的,所以这会让你得到一个从你的模板输出的消息。然而,你问的是如何将消息传递给那个模板以便它输出。这也完全很简单——你只需要在其中加入一些属性。下面是上述内容的修改版本:

主文件

import { Template } from '../template';

export class MyComponent {
  @Prop() message: string;

  render() {
    return (           
      <Template messageToOutput={message} /> // The first argument is the name of the prop, the second is the variable you defined above
    )
  }
}

模板

import React from 'react';

export const Template = (props) => { // props are received here
  return (
    <p>{props.messageToOutput}</p> // props are used here
  )
}

这就是你在 React 中传递数据的方式——希望这能帮到你!