【问题标题】:React Native set style as StateReact Native 将样式设置为 State
【发布时间】:2020-05-04 19:57:59
【问题描述】:

我想使用style1backgroundColor作为状态,并在函数change()中改变它。
如何访问style1

我的意思是从另一个函数调用函数change,使按钮的颜色变为黄色,然后在一段时间后再次将其颜色变为蓝色。

export default class App extends Component{ 
  constructor (props){
    super(props);
    this.state = {
      //style1.backgroundColour: blue  //? Can't 
    }
    this.change=this.change.bind(this)
  }

  change() {
    this.setState({ style1.backgroundColour: yellow }) //?
  }

  render(){
    return (
      <View style={styles.style1} > </View>

    );
  }
}

const styles = StyleSheet.create({

  style1:{
    padding: 5,
    height: 80,
    width: 80,  
    borderRadius:160,    
    backgroundColor:'blue',
  },

});

【问题讨论】:

    标签: javascript reactjs react-native react-native-android state


    【解决方案1】:

    你可以给样式属性一个数组。因此,您可以从其他来源添加任何其他样式。

    首先你应该为你的 backgroundColor 状态声明一个默认值:

    this.state = {
      backgroundColor: 'blue',
    };
    

    然后将它在你的函数中的状态设置为正常的字符串状态:

    this.setState({backgroundColor: 'yellow'});
    

    最后,在 style 属性中使用它:

    style={[styles.style1, {backgroundColor: this.state.backgroundColor}]}
    

    如果要使用对象,而不是字符串作为状态:

    您应该为您的样式状态声明一个默认值:

    this.state = {
      style1: {
        backgroundColor: 'blue',
      },
    };
    

    然后在你的函数中设置它的状态:

    this.setState((prevState) => {
      return {
        style1: {
          ...prevState.style1,
          backgroundColor: 'yellow',
        },
      };
    });
    

    并在 style 属性中使用它:

    style={[styles.style1, this.state.style1]}
    

    【讨论】:

    • 我收到错误 Invariant Violation: Text 字符串必须在 Text 组件中呈现。我试图删除 并将其替换为: {this.state.backgroundColor} {this.state.backgroundColor} 只是为了看看它是否改变了状态,它确实改变了。但是为什么我会收到这个错误?
    • 对不起,回答迟了:D 该错误意味着您在 View 组件等中使用了文本,或者语法错误。很可能您不小心按了一个键。我刚刚复制粘贴了我的答案并进行了测试。效果很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    相关资源
    最近更新 更多