Set React component state from outside of component

后端 未结 2 1374
遥遥无期
遥遥无期 2021-02-18 18:32

I have a list of components and want to set each component as selected when the user clicks on it.

The flow looks like

Dashboard
 ⎿ MyList
    ⎿ MyItem -         


        
2条回答
  •  南旧
    南旧 (楼主)
    2021-02-18 19:14

    By definition, state is not accessible from outside the component. And always copying props to state is not recommended.

    In your component tree structure. you should set the selected item as state in the parent (not in the item).

    And pass the selected Id to each item as a prop.

    In the child render, you can do something like

    let itemIsSelected = (this.props.itemId == this.props.selectedId);
    

    And pass a method from parent to child, and then include that as:

    onClick={() => this.props.setSelected(this.props.itemId)}
    

    In the official docs, there is a good explanation on how to structure components. This may be helpful to determine whether something should be state or props, or whether stuff is better managed inside child or parent.

提交回复
热议问题