简体   繁体   中英

React How to pass variable to component .jsx to another component jsx

I have a component bar.jsx:

render(){
        return(
          <div className="bar">
            <button className="button" onClick={() => this.setState({view: 1})}>1</button>
            <button className="button" onClick={() => this.setState({view: 2})}>2</button>
            <button className="button" onClick={() => this.setState({view: 3})}>3</button>
            <button className="button">Wallet</button>          
          </div>

And I have another component where I want to get this data:

main.jsx:

render() {
    return (
      <div className="App">
        <div className="header"></div>
        <bar></bar>
        <View></View>
      </div>
    );
  };

How to parse this.setState({view: 1}) value to my View component?

In order to do it, you need to lift your state to the main.jsx. So in main.jsx you create state {view: 0} or some other default. Then you create a function that sets this state (you cannot use this.setState in this case), it's basically a wrapper around this.setState . Then you pass this function to you bar component.

Bar component attaches it to buttons instead of () => this.setState({view: 1}) that you have.

From the main component, you pass view as a prop.

When a user clicks the button, the change function is called, the change function calls the setState in the main component. The main component's state is changed, and it changes the prop for the View component. View component renders the new data.

You can read about it more here - https://reactjs.org/docs/lifting-state-up.html

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