【问题标题】:How to pass a React component as a prop如何将 React 组件作为道具传递
【发布时间】:2017-09-06 00:49:14
【问题描述】:

我正在使用 react-semantic-ui 模态对象。 打开 modal 的对象是一个 prop。

 <Modal
       trigger=<Button>Text</Button>
       otherProp=...
   >
  </Modal>

我想在另一个组件中嵌入 Modal:

export default class Confirm extends Component {

    render() {
        return (
            <Modal
                trigger={this.props.trigger} /* here */
              >    
                <Modal.Content>
                    ...
                </Modal.Content>
                <Modal.Actions>
                    ...
                </Modal.Actions>
            </Modal>
        )
    }
}

我如何将 JSX 代码 (&lt;Button&gt;Text&lt;/Button&gt;) 作为道具传递为模态道具?

【问题讨论】:

标签: javascript reactjs semantic-ui semantic-ui-react


【解决方案1】:

您可以轻松地进行以下操作

<Modal trigger={ <Button>Text</Button> }> 
   // content goes here 
</Modal>

Modal 中,您可以通过this.props.trigger 访问它,这将是您的按钮组件,您可以像下面这样呈现它

render () {
    return (
        <div>
            // some code can go here
            { this.props.trigger }
        </div>
    );
}

【讨论】:

  • 谢谢。我的问题是如何在 Modal 标记定义中呈现 this.props.trigger。我想通过&lt;Button&gt;Text&lt;/Button&gt; 作为道具
  • 嗨@znat,我已经回答了;),您可以像任何其他字符串道具或变量一样在Modal 中打印它。 { this.props.trigger } 在您的 render 方法中
  • 我认为有一个误解:我需要这样的东西: // 内容放在这里 但这不起作用
猜你喜欢
  • 2018-08-01
  • 2018-08-22
  • 1970-01-01
  • 2020-08-20
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
相关资源
最近更新 更多