如何设置componentsDidMount中的元素样式?

时间:2016-12-21 21:38:48

标签: reactjs flickity

我有一个组件:

  render: function () {
    const item = this.props.item
    return (
            <div style={{marginTop: '20px', display: 'flex'}}>
              {item.get('images').map((url, i) =>
                  <Thumbnail href='#' src={stripUrl(url)} onClick={() => this.flky.select(i)} />
    ´          )}
            </div>
    ´    )
  }

在componentDidMount中,我希望定位其中一个thumnails并更新它的样式,我知道缩略图的索引是什么,我该怎么做?

  componentDidMount: function () {
    this.flky = new Flickity('.carousel', flickityOptions)
    this.flky.on('select', () => {
      console.log('Flickity settled at ' + this.flky.selectedIndex)
    })
  }

2 个答案:

答案 0 :(得分:2)

您可以使用状态变量来执行此操作,例如

// constructor
this.state = { mounted: false };

// componentDidMount
this.setState({ mounted: true });

// render 
<View style={ this.state.mounted ? styles.style1 : styles.style2 ></View>

答案 1 :(得分:0)

您无法直接更改组件的呈现方式,您可以做的就是修改其状态或属性,您必须设置状态的某些属性并在render方法中进行相应的呈现。 / p>

将属性设置为原始状态,例如thumbnailIndex-1,例如

getInitialState: function () {
  return {
    thumbnailIndex: -1
  };
}

渲染缩略图时,检查它是否与当前索引匹配

<Thumbnail 
  href='#' 
  style={this.state.thumbnailIndex === i ? { ...styles... } : undefined} 
  ... 
/>

componentDidMount上设置状态

的索引
this.setState({ thumbnailIndex: this.flky.selectedIndex });