【问题标题】:the changed value does not show in Dom更改的值不会显示在 Dom 中
【发布时间】:2018-06-07 11:48:38
【问题描述】:

我正在学习 React,在我的测试应用程序中,我制作了 2 组相同的随机颜色数组,每次单击“更改颜色”按钮时都会随机更改颜色。但是,即使颜色值正确更改,我似乎也无法让 Dom 更新我的数组颜色。

import React from 'react';
class Card extends React.Component{
    constructor(props){
        super(props);
        const {r,g,b}=this.props.card
        this.state={
            style:{
                width:'100px',
                height:'100px',
                display:'inline-block',
                backgroundColor:`rgb(${r},${g},${b})`
            }
        }
    }
    onClick=()=>{
        const {r,g,b}=this.props.card
        console.log('color values of the card with index',this.props.id ,' is: ', r,g,b)
    }
    render(){
        const {style}=this.state
        return (
            <div style={style}>
                <button onClick={this.onClick}>card test</button>
            </div>
        )
    }
}
export default Card;

这是我的问题的图片

正如您在图片中看到的,每次单击时值都会发生变化,但卡片的颜色保持不变。但是,如果我将基于类的组件更改为非基于类的组件并在 render() 而不是构造函数中设置样式,它将起作用,但我想要一个类组件,这样我就可以将点击的卡片传递给父组件。

【问题讨论】:

  • 您的 onClick 处理程序本质上是无操作的

标签: reactjs parameter-passing state setstate react-props


【解决方案1】:

onClick 是否也会触发其他事件?否则,看不到什么会改变卡片的值,因为 onClick 只是在记录。

假设卡片道具以某种方式正确更改,我相信您的问题是您的卡片道具正在更新,但状态是在构造函数中设置的并且从未更新。

与其在状态中设置样式值,不如在渲染中更改为计算样式。

render() {
  const {r,g,b} = this.props.card
  const style = {
    width: '100px',
    height: '100px',
    display: 'inline-block',
    backgroundColor: `rgb(${r},${g},${b})`
  }

  return (
    <div style={style}>
      <button onClick={this.onClick}>card test</button>
    </div>
  )
}

您通常不会保留很容易从 props 派生的状态以避免此类情况。

【讨论】:

  • 'change color' 按钮的 onClick 会改变颜色的值,我只是使用 Card 组件上的按钮来测试值是否正确更改,如您所见,值正确更改了道具,
  • @Nhat 道具已更改,但您并未更改 state 以反映新值!
  • 我尝试像这样使用 setState const {r,g,b}=this.props.card this.setState({backgroundColor:rgb(${r},${g},${b})}) 但它不起作用。一定是我做错了什么
  • @Nhat 你在执行componentWillReceiveProps 来更新状态吗?
猜你喜欢
  • 1970-01-01
  • 2021-05-21
  • 2018-10-06
  • 2013-12-05
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多