【问题标题】:React - Component styles not updating from propsReact - 组件样式未从道具更新
【发布时间】:2016-03-02 22:36:52
【问题描述】:

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

我正在使用父子通信技术,我在其中公开了我的第二个组件可以触发的道具功能。然后,我的第三个组件脱离了作为道具传递给它的父级的状态。

下面是我的代码(请原谅我的代码问题,因为我不得不把它撕掉并概括一下):

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

欢迎提出任何建议。

【问题讨论】:

  • componentWillReceiveProps 中,您不会传递传入的 props (nextProps),而是传递旧的 (this.props)
  • 仍然没有 :( 控制台在第三个组件渲染中注销,我可以看到更新的状态样式,即console.log(this.state.styles.rejected);
  • swipePosition 应该做什么/包含什么? getStyles() 中的任何类型的条件都没有使用它。该函数在挂载和收到新的props 时将始终生成相同的状态。 rejected 总是新创建的,accepted 总是未定义的。
  • 我使用 swipePosition 来指示我想要应用的转换,即它基本上是一个 tinder 式的左右滑动。根据当前的平移,我相应地设置了 transform - 我只放了一小部分 rejected 一个,这样你就可以看到我正在设置一个样式对象 - accepted 基本相同 - 这有意义吗?
  • 使用 componentWillReceiveProps(nextProps) { this.getStyles(nextProps.swipePosition); }

标签: javascript reactjs styles


【解决方案1】:

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

getStyles 函数中,我正在做一堆计算 - 将其应用于样式时,我忘记将 % 放入其中,因此 React 只是将其视为无效样式并忽略!

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 2020-09-15
      • 2019-09-06
      • 2019-09-16
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      相关资源
      最近更新 更多