简体   繁体   中英

How to create a controlled Fabric UI TextField component?

I've been trying to code a controlled TextField component in the standard way just like in React docs:

handleChange(event) {
    this.setState({
            text: event.target.value
    });
}

<TextField label='Enter Text' value={this.state.text} onChange={this.handleChange}/>

The code above is what I've been using, but it seems that it doesn't change the state of the react component, because in the same form if I change a controlled checkbox, it resets the textfield to be empty. If I use a standard html input element it works just as expected and doesn't clear the field.

What am I doing wrong here? Shouldn't TextField work the same way as a text type input?

From the docs , onChange is not a property. Use onChanged instead. Note that the return value is the textfield's value, not an event.

According to this example :

 handleChange(value) { this.setState({ text: value }); } 

I do not know what you want to do but ... If what you need is to pass the input value to a text label, you can do it this way:

First you must declare an interface outside of your class

interface myState {
  value1: string;
}

you must include your Interface in the class.

class TextFieldControlledExample extends React.Component<{}, myState> {...}

I suppose that for TypeScript themes you must publicly declare the interface of which you are using.

public state: myState = { value1: ''};

you must declare a function within the render to assign the value of the state

public render() {
    const { value1 } = this.state;

in this way you assign the value of your inputs. but to update it you have to create a function and call it on the onChange

<TextField
  label="Enter Text"
  value={this.state.value1}
  onChange={this._onChange}
  styles={{ fieldGroup: { width: 300 } }}
/>
<Text  variant='xxLarge' nowrap block>
  {value1}
</Text>

to assign the input value to the state you have declared using setState. must do a function.

  private _onChange = (ev: React.FormEvent<HTMLInputElement>, newValue?: string) => {
    this.setState({ value1: newValue || '' });
  };

You can see the example working here https://codepen.io/jasp402/pen/EBWBgO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM