繁体   English   中英

React-组件样式不会从props更新

[英]React - Component styles not updating from props

我目前遇到一个问题,即即使发送的道具和生成的样式实际上正在正确更新,我的一个组件( ComponentThree )样式也没有被更新。

我使用的是父子沟通技术,在这里我公开了第2个组件可以针对的props函数。 然后,我的第三个组件会脱离父级的状态,并作为道具传递给它。

以下是我的代码(请排除一些次要的编码问题,因为我不得不将其删除并泛化):

class ComponentOne extends React.Component {

  constructor(){
    super();
    this.state = {
      swipePosition: 0,
    };
  }

  handleSwipe(val, animate = false) {
    this.setState({
      swipePosition: val,
    });
  }

  render() {
    return <div className="componentOne">

      <ComponentTwo onSwipe={this.handleSwipe.bind(this)} />;

      <ComponentThree swipePosition={this.state.swipePosition} />

    </div>;
  }
}

class ComponentTwo extends React.Component {

  handlePanEnd() {
    this.props.onSwipe(percentage);
  }

  render() {
    return <Hammer onPanEnd={this.handlePanEnd.bind(this)}>
       <li>some content goes here...</li>
    </Hammer>;
  }
}

class ComponentThree extends React.Component {

  constructor(){
    super();
    this.state = {
      styles: {
        rejected: {},
        accepted: {},
      },
    };
  }

  getStyles(swipePosition) {

    // do bunch of stuff i.e. for rejected:
    const rejected = {
      WebkitTransform: 'translate3d(-100%, 0, 0)'
    }

    this.setState({
      styles: {
        rejected,
        accepted,
      },
    });
  }

  componentWillReceiveProps(nextProps) {
    this.getStyles(this.props.swipePosition);
  }

  componentDidMount() {
    this.getStyles(this.props.swipePosition);
  }

  render() {

    return <div className='ComponentThree'>
      <div style={this.state.styles.rejected}></div>
      <div style={this.state.styles.accepted}></div>
    </div>;
  }
}

任何建议欢迎。

最后真的很简单,完全是开发错误:)(可耻的尴尬)

getStyles函数中,我进行了大量计算-将其应用于样式时,我忘记了将%放入其中,因此React只是将其视为无效样式而忽略了!

如果只在渲染中计算样式,而不是将其保存在状态中,则ComponentThree会更简单。 当前,您要在坐骑和新道具出现时进行簿记,但最终结果是您拥有调用render时所需的样式。 相反,只需在render计算它们,您的大部分代码就会消失。 我怀疑您的错误是某个地方的愚蠢错误,并且通过重构,您很可能最终会删除导致您的错误的代码。

暂无
暂无

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

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