簡體   English   中英

如何將JSX導入.tsx文件(不在React中)?

[英]How do I import JSX into .tsx file (not in 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>

有可能嗎? 在此先感謝您的幫助:)

是的,您絕對可以做到這一點,您需要整理幾件事:

主文件

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中傳遞數據的方式-希望能有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM