React Native将样式设置为状态

4

我希望在函数 change()中将style1backgroundColor用作状态,并进行更改。
我该怎么访问 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',
  },

});
1个回答

6
更新:这个问题和我的回答是基于类组件的。但是现在,函数组件和钩子函数是使用 React 的当前方式已经很长时间了。
首先,您应该为您的背景颜色创建一个状态:
const [backgroundColor, setBackgroundColor] = useState('blue');

然后在您的函数中更改其值

setBackgroundColor('yellow');

最后,在样式属性中使用它:

style={[styles.style1, {backgroundColor}}

老的回答,使用类组件

你可以将样式数组传递给style属性。这样你就可以从其他来源获取任何其他样式。

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

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

然后在您的函数中将其状态设置为普通字符串状态:
this.setState({backgroundColor: 'yellow'});

最后,在样式属性中使用它:

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

我遇到了一个错误:不变式违规:文本字符串必须在Text组件中呈现。我尝试删除<View style={[styles.style1, this.state.style1]}> </View>并替换为: <Text> {this.state.backgroundColor} </Text><View> <Button onPress={this.change}> </Button> <Text> {this.state.backgroundColor} </Text> </View> 只是为了看看它是否改变了状态,而且确实改变了。但是为什么会出现这个错误? - Shiranox
抱歉回复晚了:D 这个错误意味着你在View组件等中使用了文本,或者是语法错误。很可能是你不小心按错了键。我刚刚复制粘贴了我的答案并进行了测试。它完美地工作了。 - Ugur Eren

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接