我有一个文本字段。如果状态为null,但文本字段值显示在Textfield中
<TextField
style={{ width: '65%'}}
id="standard-search"
label="Residential Address"
type="text"
margin="dense"
variant="outlined"
name="ResidentialAddress"
onChange={(e)=>this.handleInputChange(e)}
/>
答案 0 :(得分:1)
像这样value={this.state.input_value}
<TextField
style={{ width: '65%'}}
id="standard-search"
label="Residential Address"
type="text"
margin="dense"
variant="outlined"
name="ResidentialAddress"
onChange={(e)=>this.handleInputChange(e)}
value={this.state.input_value}
/>
答案 1 :(得分:0)
您需要将文本框value
绑定到状态属性。根据您使用的组件类型,您可以尝试以下选项。
对于类组件:
class YouComponentName extends Component {
constructor (props, context) {
super(props, context)
this.state = {
yourTextBoxValue: ""
}
}
handleInputChange (event) {
this.setState({
yourTextBoxValue: event.target.value;
});
}
render(){
<>
<TextField
style={{ width: '65%'}}
id="standard-search"
label="Residential Address"
type="text"
margin="dense"
variant="outlined"
name="ResidentialAddress"
onChange={(e)=>this.handleInputChange(e)}
value = {this.state.yourTextBoxValue}
/>
</>
}
对于功能组件(使用React钩子):
function YourComponentName(props) {
const [yourTextBoxValue, setYourTextBoxValue] = useState("")
const handleInputChange = (event) => {
this.setState({
setYourTextBoxValue(event.target.value);
});
}
return (
<>
<TextField
style={{ width: '65%'}}
id="standard-search"
label="Residential Address"
type="text"
margin="dense"
variant="outlined"
name="ResidentialAddress"
onChange={handleInputChange}
value = {yourTextBoxValue}
/>
</>
)
}