【发布时间】:2021-09-19 01:26:33
【问题描述】:
大家好,问题很简单。我有一个类组件,里面有两种颜色的状态。 我想创建一个 onClick 函数,当您单击它时,它会显示来自 this.state 的 2 个带有 backgroundColors 的 div。 并且按钮 MOST 在父级上 这里是代码
class Parent extends React.Component{
constructor(props){
super(props);
this.state = {
color1: "#38306b",
color2: "#fff285"
}
saveColors() = {
// thats the part i dont get.
render(){
return(
<Child />
<button onClick={() => saveColors()}>save</button>
)
class Child extends React.Component{
render(){
return(
//those divs need to appear when we click the button with saveColors().
<div style={{backgroundColor: color1 from Parent's state}}></div>
<div style={{backgroundColor: color2 from Parent's state}}></div>
)
我可以将 this.state.color1 放入一个 var 并在子组件中使用它吗?还是我应该使用返回?还是别的什么??
【问题讨论】:
-
您的代码 sn-ps 没有意义,请分享正确的代码。
标签: reactjs