【问题标题】:Change components background using ref - react native使用 ref 更改组件背景 - 反应原生
【发布时间】:2018-10-15 11:30:39
【问题描述】:

我刚刚开始学习 React Native(来自 android 背景)。我想改变 View 的背景颜色。我需要在不使用 state/props 的情况下这样做,因为我不想再次渲染它。

我已经引用了视图并且能够使用另一个按钮的 onPress() 访问它

如何更改视图的背景?

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    设置参考:

    ref={component => this.myref = component}
    

    并使用 setNativeProps 设置背景

    this.myref.setNativeProps({
        style:{backgroundColor: '#3fba29'}
    });
    

    希望这可以帮助某人:)

    【讨论】:

      【解决方案2】:

      在你使用它之前,试着用 setState 解决你的问题。

      https://reactnative.dev/docs/direct-manipulation

      单值很容易

      ChangeBackground(){
       this.setState({
        backgroundColor:'blue'
       )}
      }
      render() {
       return (  
      <View onPress={()=>this.ChangeBackground()}style={{backgroundColor:'red'}}>
        ....
       </View>
      

      在数组数据中,您必须使用索引值。借助 index 或 id 更新背景颜色

      类似的,

      const original = this.state.array;
      const single_array = this.state.array.find(
          x => x.id === id,
      );
      single_array.backgroundColor = 'blue';
      original[index] = single_array;
      this.setState({
          array: original,
      });
      

      【讨论】:

        猜你喜欢
        • 2021-06-14
        • 2018-05-04
        • 2020-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 2022-06-11
        相关资源
        最近更新 更多