简体   繁体   English

ReactJS-以默认状态渲染

[英]ReactJS - render with default state

How can I rerender component with state from getInitialState() ? 如何从getInitialState()渲染具有状态的组件?

For example: https://jsbin.com/pajapoyipo/edit?html,output 例如: https : //jsbin.com/pajapoyipo/edit?html,输出

In example code I click on the button, component Button change state and button is Yellow - its work, but when I click on another button I would like to clicked the button was yellow (its work), and the old button changed state and color to red (it doesn't work). 在示例代码中,我单击了按钮,组件Button的状态更改了,按钮是黄色的-它起作用了,但是当我单击另一个按钮时,我想单击的按钮是黄色的(它起作用了),而旧按钮改变了状态和颜色变成红色(无效)。

Avoid stuff like this: 避免这样的事情:

childState.setState({klasa: "yellow"});

You should not be setting child state from the parent. 您不应从父级设置子级状态。 State is internal to a component, it should only be changed by itself. 状态是组件内部的状态,只能自行更改。 Instead, the parent can re-render the child with different props. 相反,父母可以用不同的道具重新渲染孩子。

If you want only one button to be active, then you have to have some piece of state that will only permit a single active button. 如果只希望一个按钮处于活动状态,则必须具有某种状态,该状态仅允许一个活动按钮。 Since children can't know about their fellow siblings, this piece of state must reside in the parent. 由于孩子们不了解他们的同胞兄弟姐妹,因此这种状态必须存在于父母中。 I've called it activeBtn . 我称它为activeBtn If activeBtn is 1, then the first button appears yellow. 如果activeBtn为1,则第一个按钮显示为黄色。 This piece of state in the parent corresponds to the boolean property active in child. 父级中的这种状态对应于子级中active的布尔属性。 I've also defined a click handler in the parent to change the state. 我还在父级中定义了一个单击处理程序以更改状态。 This click handler is passed down to each child as a prop. 该点击处理程序作为道具传递给每个孩子。

If that doesn't make sense, the modified code should serve as a better explanation: https://jsbin.com/filasisemu/1/edit?html,output 如果那没有意义,则修改后的代码应作为更好的解释: https : //jsbin.com/filasisemu/1/edit?html,输出

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

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