React-Native - 以编程方式更改组件的样式(无单击)

Tho*_*mar 6 reactjs react-native

假设<Text></Text>连续有10个组件.这些组件将通过循环遍历数组来创建,如下所示:

...
const fontsize = 16
return (
  <View style={{flex: 1}}>
    {
      array.map((val, index, arr) => {
        return (
          <Text ref={'text' + index} style={{fontSize: fontsize}]}>{val}</Text>
        )
      })
    }
  </View>
)
...
Run Code Online (Sandbox Code Playgroud)

现在我想改变的fontSize的<Text>与组件裁判'text5'

我知道我可以获取/设置此组件的样式,this.refs.text5.props.style.fontSize但我如何更新虚拟DOM?

Jos*_*ark 7

使用状态:https://facebook.github.io/react-native/docs/state.html

调用this.setState将使用更新的状态重新呈现视图.

例如

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fontizes: [16, 127, 2, ...]
    };
  }

  setFontsize(size, index) {
    let current = this.state.fontsizes;
    current[index] = size;
    this.setState({ fontsizes: current });
  }

  render() {
    return (
      <View style={{flex: 1}}>
        {
          array.map((val, index, arr) => {
            return (
              <Text ref={'text' + index} style={{fontSize: this.state.fontsizes[index]}]}>{val}</Text>
            )
          })
        }
      </View>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)