简体   繁体   中英

How to pass a React component as a prop

I'm using react-semantic-ui Modal object. The object that opens the modal is a prop.

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

I want to embed Modal in another component:

export default class Confirm extends Component {

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

How can I pass JSX code ( <Button>Text</Button> ) as a prop to be render as a Modal prop?

You can easily do following

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

and inside Modal , you can access it via this.props.trigger which will be your button component and you can render it like below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM