Passing data between two sibling React.js components

前端 未结 2 1048
时光取名叫无心
时光取名叫无心 2020-12-30 07:03

I have two instances of a component (a search field) on a page, with a second component (a button that makes server calls) between them, as such:

2条回答
  •  独厮守ぢ
    2020-12-30 07:33

    I created a jsfiddle with an example of how to share a variable between two components using a parent component.

    class Parent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {shared_var: "init"};
        }
    
        updateShared(shared_value) {
            this.setState({shared_var: shared_value});
        }
    
        render() {
            return (
                
    The shared value is {this.state.shared_var}
    ); } } class CardSearch extends React.Component { updateShared() { this.props.updateShared('card'); } render() { return ( ); } } class RunOnServer extends React.Component { updateShared() { this.props.updateShared('run'); } render() { return ( ); } } ReactDOM.render( , document.getElementById('container') );

提交回复
热议问题