用饮料按钮打开"你好"世界,用食物按钮打开"再见"世界



//hello当我点击饮料时,问题出现了控制台hello world再见世界togather,当我点击食物时,它显示hello world goobye world togather也是

class Item extends React.Component {
constructor()  {
super();
this.state = {
Card1: 0
} ;
this.state = {
Card2: 0
};
}
handleClick = (button) => {
this.setState({ Card1: button })
};
handel = (event) => {
this.setState({ Card2: event })
}
render() {
return (
<div>
<button onClick={() => this.handleClick(1)}>drink</button>
<button onClick={() => this.handel(1)}>food </button>
<div>
{this.state.handel ? console.log("goodbye world") : console.log("null")}
{this.state.handleClick  ? console.log('hello world') : console.log("null")}
</div>
</div>
);
}
}
export default Item;

欢迎使用堆栈溢出。只是一些基本错误。

构造函数中应该只有一个状态变量。

this.state = {
Card1: 0,
Card2: 0,
};

在渲染中,您应该检查状态变量,然后打印到控制台。你是字符串来检查未定义的东西。

{this.state.Card2 ? console.log("goodbye world") : console.log("null")}
{this.state.Card1 ? console.log('hello world') : console.log("null")} 

如果这对你有意义,请告诉我。

您的代码中有很多问题。

在您的代码状态中,初始化不正确,这是错误的构造函数。不需要在中声明两次状态初始化一个组件。

事件处理程序不正确。

您正在将state设置为card1和card2,但正在检查handler像this.state.handle这样的函数是不正确的。

在您的情况下,使用布尔值而不是使用0和1。

有意义根据按钮的状态和处理程序功能的全名

您应该执行以下操作。

class Item extends React.Component {
constructor()  {
super();
this.state = {
drink: false,
food: false
} ;
}
handleDrink = () => {
this.setState({ drink: true, food: false })
};
handleFood = () => {
this.setState({ food: true, drink: false })
}
render() {
const { drink, food } = this.state;
return (
<div>
<button onClick={() => this.handleDrink()}>drink</button>
<button onClick={() => this.handleFood()}>food </button>
<div>
{drink && console.log("goodbye world")}
{food  && console.log('hello world')}
</div>
</div>
);
}
}
export default Item;

最新更新