简体   繁体   中英

Pass variable from one component to another ReactJS

I am woking on a sample ReactJS application, where I want to pass a variable from one component to another.

class Layout extends React.Component{
    constructor(props) {
        super(props);
        this.state = {keyword: ''};
    }
    render() {
        return (
                 <div className="wrapper">
                   <Search />
                   <Listing />
                  </div>
        );
    }
};

ReactDOM.render(
    <Layout />, app
); 

In the above code, I want to pass a variable from <Search /> component to <Listing /> component.

You can make it with function like

class Layout extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            keyword: '',
            yourVariable: null
        };
    }
    sendVariable(newValue) {
        this.setState({ yourVariable: newValue });
    }
    render() {

        return (
            <div className="wrapper">
                <Search onChange={this.sendVariable.bind(this)} />
                <Listing sendValue={this.state.yourVariable} />
            </div>
        );
    }
};

class Search extends React.Component{
    render(){
        let variable = "";
        return <div onClick={this.porps.onChange(variable)}></div>;
    }
}

Or use React-redux .

Rlijo you'd pass props to components as follows:

<Search paramA={someParam} paramB={anotherParam} /> and to use the props within the Search component you'd call this.props.paramA (if using classes).

The way you've got the components setup, you wouldn't be able to share the state from the Search component (ie the object in this.state within Search) with the Listing component. There are libraries such as Redux designed to solve problems of shared state across components.

Props (or variables or params) flow downward so you'd need to provide shared props from a parent component. See you could provide this.state.keyword as a prop to both Search and Listing as these two components sit inside this parent component.

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