如何删除TextField状态

时间:2019-10-30 09:39:13

标签: javascript reactjs material-ui

我有一个文本字段。如果状态为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)}
                    />

2 个答案:

答案 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}
            />
        </>
    )
}