首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >每次按下按钮时,react setState not rendering

每次按下按钮时,react setState not rendering
EN

Stack Overflow用户
提问于 2021-09-18 02:26:32
回答 1查看 44关注 0票数 0

我尝试使用setState来访问我的css const mystyle对象,以便将正方形上的背景色从蓝色更改为红色,但每次按下按钮时。似乎每次我按下按钮时,Setstate都不会在屏幕上显示任何建议或帮助?将不胜感激

代码语言:javascript
复制
class MyHeader extends React.Component {

  constructor(props){
    super(props)
    this.state = {backgroundColor: 'blue'};
  }

  
  render() {
    const mystyle = {
    borderRadius: "10px",
    background: this.state.backgroundColor,
    padding: "10px",
    width: "100px",
    height: "100px",
    marginTop: "10px",
    lineHeight: "80px",
    color: "dimGrey",
    fontWeight: "bold",
    fontSize: "3em",
    textAlign: "center"
  };
     
  function State() {
    this.setState({backgroundColor: 'red'})
  }

    return (
      <div>
      <h1 style={mystyle}></h1>
        <h1>{this.state.backgroundColor}</h1>
      </div>
    );
  }
}


function Test() {
  
  function Test2() {
    setchange(change + Math.floor(Math.random() * 10));
    if(change > 20) {
      setchange(change + Math.floor(Math.random() - 10))
    }
  }
  
  const [change, setchange] = React.useState(1)
    return (
        <div>
        <h1>click the button to randomize colors</h1>
        <button onClick={this.State}>Randomize colors!</button>
        <div className='.flex-item'></div>
        <h1>{change}</h1>
       <div className="flex-item"></div>
        
        <MyHeader />
        <MyHeader />
   
        </div>
    );
}



ReactDOM.render(<Test />, document.getElementById("root"));

my codepen link to the code

EN

回答 1

Stack Overflow用户

发布于 2021-09-18 03:01:18

主要的问题是试图做一些事情,其中子组件MyHeader具有更改状态的功能,但试图从父组件Test调用它。将颜色作为道具从Test传递到MyHeader会更简单。

或者,您也可以使用useContext,但我认为这会更简单。我已经剔除了所有不被使用的多余代码。当然,您可以根据需要重新添加它们。

代码语言:javascript
复制
const MyHeader = ({backgroundColor}) => {
  
    const mystyle = {
      borderRadius: "10px",
      background: backgroundColor,
      padding: "10px",
      width: "100px",
      height: "100px",
      marginTop: "10px",
      lineHeight: "80px",
      color: "dimGrey",
      fontWeight: "bold",
      fontSize: "3em",
      textAlign: "center"
    };
     
    return (
      <div>
      <h1 style={mystyle}></h1>
        <h1>{backgroundColor}</h1>
      </div>
    );
  }
}

const Test = (props) => {

  const [backgroundColor, setBackgroundColor] = useState("blue");
 
  const onButtonClick = () => {
      setBackgroundColor("red");
  }

  return (
        <div>
          <h1>click the button to randomize colors</h1>
          <button onClick={onButtonClick}>Randomize colors!</button>
          <div className='.flex-item'></div>
          <h1>{change}</h1>
          <div className="flex-item"></div>
          <MyHeader backgroundColor={backgroundColor} />
       </div>
    );

};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69231121

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档