【问题标题】:How to import jsx with state variables into another react component?如何将带有状态变量的 jsx 导入另一个反应组件?
【发布时间】:2018-11-09 21:10:14
【问题描述】:

我有一个 react 组件,我想将一个长 JSX 代码导入其中。然而,JSX 有包含 this.state.example 的变量。如何导入?

这是一个例子:

class CompA extends Component {
state={displaying:false}; render(){const {displaying}=this.state; return({x})}
}

将此文件导出到顶部?

export const x = (
<div>displaying</div>
)

【问题讨论】:

    标签: javascript node.js reactjs export frontend


    【解决方案1】:

    将 x 设为无状态子组件。

    //x.jsx
    export const X = ({displaying})=>(
     <div>{displaying}</div>
    )
    
    import {X} from "./x.jsx";
    class CompA extends Component {
     state={displaying:false}; 
     render(){
      const {displaying}=this.state; 
      return <X displaying={displaying}/>
     }
    }
    

    【讨论】:

      【解决方案2】:

      X 应该是一个“虚拟”或函数式(因为它们被称为)React 组件:

      const X = ({displaying}) => (
        <div> {displaying} </div>
      );
      

      所以外部文件应该是这样的:

      import React from 'react';
      
      const X = ({displaying}) => (
        <div> {displaying} </div>
      );
      
      export { X };
      

      X 组件现在可以像任何其他 React 组件一样正常调用,例如:

      <X displaying="This is the text displayed" />
      

      现在你可以像这样导入它:

      import { X } from './pathToJSFile'
      

      并在你的组件中使用它:

      class CompA extends Component {
          constructor(props) {
              super(props);
              this.state.displaying = false;
          }
      
      
          render() {
              return( 
                  <X displaying={this.state.displaying} /> 
              );
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-22
        • 1970-01-01
        • 1970-01-01
        • 2019-02-26
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多