react组件之间的消息传递

    在react中,父子组件可以通过props来传递消息。而在实际开发中经常会遇到几个组件需要共享数据的情况,react提供的一种方法就是将他们共享的状态提升至离他们最近的父组件中进行统一管理。这种机制称为“状态提升”。

    这里用一个例子来具体说明。假设我们有两个输入框,在其中任何一个输入框中输入内容,另一个框中的内容也会随着改变。每个输入框都是一个组件,这就涉及到组件之间的信息传递。因此我们创建一个状态管理组件作为这两个输入组件的父组件来统一管理状态。 body部分的代码如下:

<body>
<div id="root"></div>
<script type="text/babel">
    class InputBox extends React.Component {
        constructor(props) {
            super(props);
            this.handleChange = this.handleChange.bind(this);
        }

        handleChange(e) {
            this.props.inputChange(e.target.value);
        }

        render() {
            const input= this.props.input;
            return (<form>
                        <label for="input">input something:</label>
                        <input id="input" value={input} onChange={this.handleChange}/>
                    </form>
            );
        }
    }
    class Control extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                input: ''
            };
            this.handleChange = this.handleChange.bind(this);
        }

        handleChange(input) {
            this.setState({input: input});
        }

        render() {
            return (
                    <div>
                        <InputBox inputChange={this.handleChange} input={this.state.input}/>
                        <InputBox inputChange={this.handleChange} input={this.state.input}/>
                    </div>
            )
        }
    }
    ReactDOM.render(
            <Control/>,
        document.getElementById('root')
    )
</script>
</body>
    由以上代码可以看到,InputBox组件中,当输入发生变化时,绑定的onChange事件是一个从父组件传递过来的函数。而这个函数的具体执行位置在父组件中,同时在父组件中改变了input状态,然后再传递给子组件。使得各子组件重新渲染。以此实现了兄弟节点的消息传递。




    

猜你喜欢

转载自blog.csdn.net/u013910340/article/details/80249612