Passing data between two sibling React.js components

前端 未结 2 1040
时光取名叫无心
时光取名叫无心 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:08

    As of 2020, Feb; Context API is the way to handle this:

    // First you need to create the TodoContext
    
    
    // Todo.jsx
    //...
    export default () => {
      return(
        <>
          <TodoContextProvider>
            <TodoList />
            <TodoCalendar />
          </TodoContextProvider>
        </>
      )
    }
    
    // Now in your TodoList.jsx and TodoCalendar.jsx; you can access the TodoContext with:
    //...
    const todoContext = React.useContext(TodoContext);
    console.log(todoContext)
    //...
    //...
    
    

    Check this video tutorial by The Net Ninja for Hooks & Context API

    Good Luck...

    0 讨论(0)
  • 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 (
                <div>
                    <CardSearch shared_var={this.state.shared_var} updateShared={this.updateShared} />
                    <RunOnServer shared_var={this.state.shared_var} updateShared={this.updateShared} />
                    <div> The shared value is {this.state.shared_var} </div>
                </div>
            );
        }
    }
    
    class CardSearch extends React.Component {
        updateShared() {
            this.props.updateShared('card');
        }
    
        render() {
            return (
                <button onClick={this.updateShared} style={this.props.shared_var == 'card' ? {backgroundColor: "green"} : null} >
                card
                </button>
            );
        }
    }
    
    class RunOnServer extends React.Component {
        updateShared() {
            this.props.updateShared('run');
        }
    
        render() {
            return (
                <button onClick={this.updateShared} style={this.props.shared_var == 'run' ? {backgroundColor: "green"} : null}>
                run
                </button>
            );
        }
    }
    
    
    ReactDOM.render(
      <Parent/>,
      document.getElementById('container')
    );
    
    0 讨论(0)
提交回复
热议问题