我不断收到一条错误消息,说 this.replaceState 不是函数

现在我有一个学校项目要在我的手机上构建一个应用程序。我们正在使用 React Native 和 Java。我想在应用程序中制作一个按钮,按下时会变为随机颜色。然而,这不起作用。


这是我的一些代码片段:


    export default class HomeScreen extends React.Component {


  constructor(props) {

  super(props);

  this.state = {color: "#000000"}

}

  render() {


    let color = this.state.color;

  return (


...


<View>

          <Button

          onPress = {changecolor}

          title = "This button changes color when pressed"

          color = {color}/>

        </View>


...


numbers = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];


this.random = this.numbers[Math.floor(Math.random() * this.numbers.length)];


function changecolor() {

  this.replaceState({color: String("#"+random+random+random+random+random+random)});


在此之前我也遇到了一个问题,该按钮只会变成灰色阴影而不是任何颜色。请问有什么帮助吗?


编辑:我应该提到我之前使用过 this.setState 并且结果相同


繁星coding
浏览 195回答 2
2回答

墨色风雨

export default class HomeScreen extends React.Component {&nbsp; &nbsp; constructor(props) {&nbsp; &nbsp; &nbsp; &nbsp; super(props);&nbsp; &nbsp; &nbsp; &nbsp; this.state = {color: "#000000"}&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; let color = this.state.color;&nbsp; &nbsp; return (&nbsp; &nbsp; <View>&nbsp; &nbsp; &nbsp; &nbsp; <Button&nbsp; &nbsp; &nbsp; &nbsp; onPress = {this.changecolor}&nbsp; &nbsp; &nbsp; &nbsp; title = "This button changes color when pressed"&nbsp; &nbsp; &nbsp; &nbsp; color = {color}/>&nbsp; &nbsp; </View>&nbsp; &nbsp; numbers = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];&nbsp; &nbsp; this.random = this.numbers[Math.floor(Math.random() * this.numbers.length)];&nbsp; &nbsp; changecolor() {&nbsp; &nbsp; &nbsp; &nbsp; this.replaceState({color: String("#"+random+random+random+random+random+random)});&nbsp; &nbsp; }}&nbsp;

杨魅力

changecolor甚至是班级成员HomeScreen?看起来不像,考虑到它是用声明的function并且没有解析错误对你大喊大叫。让它成为一个方法,更好的是,一个箭头函数:changecolor = () => {&nbsp; this.replaceState({color: String("#"+random+random+random+random+random+random)});}&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript