我想将文本输入上的值连接到状态中的属性上,但我不知道如何从单击事件中访问该输入的值。
这是我现在正在使用的代码。
onCreateClick = () => {
const valueFromInput =
this.setState((prevState) => {
stateProperty: prevState.stateProperty.concat(`${valueFromInput}`)
})
}
这里有一个如何做到这一点的例子,我使用了功能组件和钩子,而不是基于类的组件,但我希望您了解实现背后的逻辑:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [stateProperty, setStateProperty] = useState("");
const [valueFromInput, setValueFromInput] = useState("");
const onCreateClick = () => {
let newString = stateProperty;
setStateProperty(newString.concat(valueFromInput));
setValueFromInput("");
console.log(valueFromInput);
};
return (
<div className="App">
{stateProperty ? stateProperty : "Type Something"}
<input
value={valueFromInput}
onChange={(e) => setValueFromInput(e.target.value)}
/>
<button onClick={onCreateClick}>append</button>
</div>
);
}
Codesandbox示例
您可以在要获取其值的JSX元素上设置引用。然后,您可以在事件处理程序中引用DOM元素。一旦有了对该DOM元素的引用,就可以像普通HTML元素一样,用yourElement.value
获取输入的值。
https://reactjs.org/docs/refs-and-the-dom.html
从React文档复制
带挂钩的功能组件
function CustomTextInput(props) {
// textInput must be declared here so the ref can refer to it
const textInput = useRef(null);
function handleClick() {
textInput.current.focus();
}
return (
<div>
<input
type="text"
ref={textInput} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}
类组件实现
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}```