gpt4 book ai didi

javascript - Onclick不显示表单 react

转载 作者:行者123 更新时间:2023-12-02 21:52:12 24 4
gpt4 key购买 nike

当您按下编辑按钮时,我试图显示一个表单。在我的控制台中,我看到 PRESSED!!!,但表单未显示。我不需要绑定(bind),因为我使用箭头函数。即使我删除表单并放置 H1 标签,它仍然不显示。可能是什么问题?

 addForm = () => {
const { title } = this.state;
<form onSubmit={this.handleSubmit}>
<label>Enter the title of the book!</label>
<input type="text" name="title" value={title} onChange={this.handleChange} />
<button type="submit" className="btn btn-success mr-1 mt-1">Add Book!</button>
</form>
console.log("PRESSED!!!")
}


selectButton = () => {
if (this.props.typeButton == "CRUD") {
return (
<React.Fragment>
<button className="btn btn-success mr-1 mt-1" onClick={this.addForm}>Add</button>
<button className="btn btn-warning mr-1 mt-1">Edit</button>
<button className="btn btn-danger mr-1 mt-1">Delete</button>
</React.Fragment>);



}
}

最佳答案

onClick 中的函数包含 JSX,而不是逻辑。您应该向状态添加一个 bool 值来指示是否应显示表单,并在单击时更新它。然后,有条件地显示它,就像您对 selectButton 所做的那样本身(我猜它是一个类组件,对吧?)

addForm = () => {
const { title, showForm } = this.state;

if (showForm)
return (
<form onSubmit={this.handleSubmit}>
<label>Enter the title of the book!</label>
<input type="text" name="title" value={title} onChange={this.handleChange} />
<button type="submit" className="btn btn-success mr-1 mt-1">Add Book!</button>
</form>
);
}


selectButton = () => {
if (this.props.typeButton == "CRUD") {
return (
<React.Fragment>
<button className="btn btn-success mr-1 mt-1" onClick={this.setState({...this.state, showForm: true})}>Add</button>
<button className="btn btn-warning mr-1 mt-1">Edit</button>
<button className="btn btn-danger mr-1 mt-1">Delete</button>
</React.Fragment>
);
}
}

render() {
return (<>
{selectButton()}
{addForm()}
</>);
}

顺便说一句,<></><React.Fragment></React.Fragment> 的简短语法

关于javascript - Onclick不显示表单 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60104430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com