单击按钮时从输入中获取值
Get the value from input when button is clicked
有这个代码片段:
const MyComponent = ({ e }) => {
const toggleButton = (e) => {
console.log('eee: ', e.target.value);
};
return (
<div>
<div>
<input className='input-search' type='text' placeholder='search' />
<Button onClick={(e) => toggleButton(e)}>reset</Button>
</div>
</div>
);
};
我期待在日志中看到输入的值,但它是 undefined
。有什么想法吗?
e.target
是没有值属性的按钮。您应该 storing the input value in state with a onChange
event. Make sure that the input's value attribute reflects the state, and use useEffect
将更改记录到控制台。
const {useState, useEffect} = React;
function Example() {
const [input, setInput] = useState('');
useEffect(() => {
console.log(`State: ${input}`);
}, [input])
function handleClick() {
setInput('');
}
function handleInput(e) {
const { target: { value } } = e;
setInput(value);
}
return (
<div>
<div>
<input onChange={handleInput} type="text" placeholder="search" value={input} />
<button onClick={handleClick}>reset</button>
</div>
</div>
);
};
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
有这个代码片段:
const MyComponent = ({ e }) => {
const toggleButton = (e) => {
console.log('eee: ', e.target.value);
};
return (
<div>
<div>
<input className='input-search' type='text' placeholder='search' />
<Button onClick={(e) => toggleButton(e)}>reset</Button>
</div>
</div>
);
};
我期待在日志中看到输入的值,但它是 undefined
。有什么想法吗?
e.target
是没有值属性的按钮。您应该 storing the input value in state with a onChange
event. Make sure that the input's value attribute reflects the state, and use useEffect
将更改记录到控制台。
const {useState, useEffect} = React;
function Example() {
const [input, setInput] = useState('');
useEffect(() => {
console.log(`State: ${input}`);
}, [input])
function handleClick() {
setInput('');
}
function handleInput(e) {
const { target: { value } } = e;
setInput(value);
}
return (
<div>
<div>
<input onChange={handleInput} type="text" placeholder="search" value={input} />
<button onClick={handleClick}>reset</button>
</div>
</div>
);
};
// Render it
ReactDOM.render(
<Example />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>