React.js - Communicating between sibling components

前端 未结 2 1021
春和景丽
春和景丽 2020-11-27 16:25

I\'m new to React, and I\'d like to ask a strategy question about how best to accomplish a task where data must be communicated between sibling components.

First, I\

2条回答
  •  醉酒成梦
    2020-11-27 17:16

    TLDR: Yes, you should use a props-from-top-to-bottom and change-handlers-from-bottom-to-top approach. But this can get unwieldy in a larger application, so you can use design patterns like Flux or Redux to reduce your complexity.

    Simple React approach

    React components receive their "inputs" as props; and they communicate their "output" by calling functions that were passed to them as props. A canonical example:

    
    

    You pass the initial value in one prop; and a change handler in another prop.

    Who can pass values and change handlers to a component? Only their parent. (Well, there is an exception: you can use the context to share information between components, but that's a more advanced concept, and will be leveraged in the next example.)

    So, in any case, it's the parent component of your selects that should manage the input for your selects. Here is an example:

    class Example extends React.Component {
    
        constructor(props) {
            super(props);
            this.state = {
                // keep track of what is selected in each select
                selected: [ null, null, null ] 
            };
        }
    
        changeValue(index, value) {
            // update selected option
            this.setState({ selected: this.state.selected.map((v, i) => i === index ? value : v)})
        }
    
        getOptionList(index) {
            // return a list of options, with anything selected in the other controls disabled
            return this.props.options.map(({value, label}) => {
                const selectedIndex = this.state.selected.indexOf(value);
                const disabled = selectedIndex >= 0 && selectedIndex !== index;
                return {value, label, disabled};
            });
        }
    
        render() {
            return (
    this.changeValue(1, v)} />
    提交评论

提交回复
热议问题