简体   繁体   English

如何更改反应中 3 个组件中的 1 个的 state

[英]how to change state of 1 out of 3 components in react

I have the following layout.我有以下布局。

<ParentComponent>
  |ComponentA
  |ComponentA
  |ComponentA

Basically I call the same Component 3 times in the parent component because they are very similar but just have different values.基本上我在父组件中调用相同的组件 3 次,因为它们非常相似但只是具有不同的值。 I was told I need to put a button on the parent component to change the values of just one out of the 3 ComponentA.有人告诉我,我需要在父组件上放置一个按钮来更改 3 个 ComponentA 中的一个的值。 ComponentA is called 3 times to give me the same thing 3 times, if I make a button to set the state of one, it will go to all 3. How can I single out one component? ComponentA 被调用 3 次给我同样的东西 3 次,如果我做一个按钮来设置 state 为一个,它将 go 到所有 3. 我怎样才能挑出一个组件?

Thanks!谢谢!

Make an array of props you want to send to your components, and then change the content of that array on some button/input events, as your application demands it.制作一个要发送到组件的 props 数组,然后根据应用程序的需要在某些按钮/输入事件上更改该数组的内容。

For example:例如:

const arrOfProps = [{someProp:'aaa'}, null, null]

const someFunc = (num)=>{
    arrOfProps.forEach((x, index)=>{
        if (index === num) {x = {someProp:'aaa'}}
        else { x = null}
    })
}

render(){
    return(
    <div>
        <button onClick={()=>someFunc(0)}>One</button>
        <button onClick={()=>someFunc(1)}>Two</button>
        <button onClick={()=>someFunc(2)}>Three</button>
        <ParentComponent>
            <div>{arrOfComponents.map((comp, index)=>{
                return <ComponentA key={index} prop={comp}/>
            })}</div>
        </ParentComponent>
    </div>)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM