更改的值不会显示在Dom中

问题描述 投票:1回答:1

我正在学习React,在我的测试应用程序中,我制作了两组相同的随机彩色数组,每次点击“更改颜色”按钮时都会改变颜色并改变颜色。但是我似乎无法让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;

这是我的问题的图片

enter image description here

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

reactjs parameter-passing state setstate react-props
1个回答
4
投票

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>
  )
}

你通常不知道什么保持状态容易从道具派生,以避免这样的情况。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.