使用状态在React中显示/隐藏组件

3
我想在检查状态值时隐藏/显示一个组件:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Button from '@material-ui/core/Button'

class App extends Component {
    constructor(props) {
        super(props);
        this.state = true;
    }

    render() {    
        return (
          <div className="App">
            {this.state && <Button variant="raised" onClick={this.state=false}>Button</Button>}

          </div>
        );
    }
}

export default App;

我不知道哪里出了问题或者是哪段代码有误,但是渲染似乎没有刷新。

1
你需要提供一个函数给onClick属性。this.state=false显然不是一个函数。你还需要使用setState方法而不是直接设置。如果可以的话,最好将状态设置为对象。 - gorhawk
3个回答

7
您使用方式不正确。您必须像这样初始化状态:
constructor(props) {
  super(props);
  this.state = {show: true}
}

并将其呈现如下
return (
    <div className="App">
        {this.state.show && <Button variant="raised" onClick={() => this.setState({show:false})}>Button</Button>}

      </div>
);

0
在 React 组件中,this.state 应该是一个表示组件状态的对象。
1) this.state 必须被初始化(可以在构造函数或类体中)。
例如,在构造函数中:
constructor(props) {
    super(props);
    this.state = {
        showButton: true
    };
}

2) 事件处理程序必须是组件方法的引用(this.handleButtonClick),并且此方法必须绑定到组件实例:

constructor(props) {
    super(props);
    this.state = {
        showButton: true
    };
    this.handleButtonClick = this.handleButtonClick.bind(this);
}
handleButtonClick(event) {
    this.setState(() => ({ showButton: false }));
}
render() {

    return (
        <div className="App">
            {this.state.showButton && <Button variant="raised" onClick={this.handleButtonClick}>Button</Button>}

        </div>
    );
}

请注意,您不应直接设置状态,而应使用setState方法。我使用的setState签名是更新程序表单,请查看React文档以了解其说明。

0

你不能将this.state声明为一个变量,这会在编译时返回错误。就像Murat所说的那样。

在React中,状态是一个JS对象,并且被声明为如下:

this.state = { ... }

为了改变状态,你不能直接在React中进行更改,否则React将不知道它已经发生了变化。如果你想要声明你的状态为:

this.state = {show: true}

然后想要将布尔值更改为false,你不能简单地使用this.state.show = false来实现。React不会知道这个变化已经发生了,这就是为什么你需要使用一个叫做setState()的React方法。就像Murat所说的那样,你可以通过以下的onClick方法来改变状态:onClick={() => this.setState({show:false})}

你应该查看这个关于React状态的文档页面,它是使用React.JS的重要部分。

https://reactjs.org/docs/state-and-lifecycle.html

这篇文章有一节叫做“正确使用状态”,你可以看一下。 :)

非常感谢! - Zenyo

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