gpt4 book ai didi

javascript - 输入表单后 react 条件显示/隐藏不起作用

转载 作者:行者123 更新时间:2023-12-02 22:17:04 27 4
gpt4 key购买 nike

提前感谢您的帮助。我试图制作基于 const results 显示按钮的组件,但是当我插入: Balaton 时,它仅在我向字符串插入另一个字符后才显示。所以字符串是 ```Balatons``

import React from 'react';
import { BrowserRouter, Link as Router, Route, Link } from 'react-router-dom';

//STYLES
import './Search.css';

// COMPONENTS
import Gallery from '../Gallery/Gallery';
import Present from '../Present/Present';

const results = ["Balaton", "Zamardi", "Sound", "Madarsko", "Sziget", "Hungary"]

class Search extends React.Component {
state = {
input: '',
showButton: false
};

onInput = (event) => {
this.setState({
input: event.target.value})
console.log(this.state.input)
console.log(this.state.submit)

// Conditional input to render button
if (results.indexOf(this.state.input) > -1) {
this.setState({
showButton: true
})
} else {
this.setState({
showButton: false
})
}
}

// TODO
// Handling submit event
onSubmit = (event) => {
console.log(this.state.submitted);
event.preventDefault()
}


render() {

return(
<div>
<form className="search-form" onSubmit={this.onSubmit}>
<input
type="text"
value={this.state.input}
placeholder="Our great memory"
onChange={this.onInput}
/>
{this.state.showButton && <button>Button</button>}
</form>
</div>)

}
}

export default Search;

最佳答案

setState 是异步方法,因此当您测试 this.state.input 时,您会得到旧值。尝试使用这个:

// ....
onInput = (event) => {
const eventValue = event.target.value;
this.setState({
input: eventValue })
console.log(eventValue )
console.log(this.state.submit)

// Conditional input to render button
if (results.indexOf(eventValue) > -1) {
this.setState({
showButton: true
})
} else {
this.setState({
showButton: false
})
}
}
// ....

或者您可以使用setState回调函数:

// ....
onInput = (event) => {
this.setState({
input: event.target.value }, ()=> {
console.log(this.state.input)
console.log(this.state.submit)

// Conditional input to render button
if (results.indexOf(this.state.input) > -1) {
this.setState({
showButton: true
})
} else {
this.setState({
showButton: false
})
}
})
}
// ....

关于javascript - 输入表单后 react 条件显示/隐藏不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59357876/

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