繁体   English   中英

反应:组件中的动态 styles 未更新

[英]React: Dynamic styles in component not updating

我正在尝试根据其道具制作具有动态大小的组件。 目前,我正在使用以下设置对其进行测试,但是当我调整 slider 时,组件不会改变大小

// View.js
import React, { Component } from 'react';
import Cell from './Cell'

export default class View extends Component {
  constructor(props) {
    super(props);

    this.handleSlide = this.handleSlide.bind(this);

    this.state = {
      cellSize: 50
    };
  }

  handleSlide(event) {
    this.setState({
      cellSize: event.target.value
    });
  }

  render() {
    return (
      <div>
        <input type="range" min="1" max="100" value={this.state.cellSize} onChange={this.handleSlide} />

        <Cell size={this.state.cellSize}/>

      </div>
    );
  }
}
// Cell.js
import React, { Component } from 'react';

export default class Cell extends Component {

  render() {
    const cellSize = {
      width: this.props.size,
      height: this.props.size
    }

    return (
      <div style={cellSize}>
      </div>
    );
  }
}

我究竟做错了什么

您缺少widthheight属性的单位。 您可以使用模板文字

const cellSize = {
   width: `${this.props.size}px`,
   height: `${this.props.size}px`,
};

字符串连接

const cellSize = {
   width: this.props.size + 'px',
   height: this.props.size + 'px',
};

暂无
暂无

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

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