[英]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: 我一直在尝试以标准方式编写受控TextField组件,就像在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. 上面的代码是我一直在使用的,但它似乎并没有改变react组件的状态,因为如果我更改一个受控复选框,它会以相同的形式重置,它会将textfield重置为空。 If I use a standard html input element it works just as expected and doesn't clear the field.
如果我使用标准的html输入元素,它的工作方式与预期的一样,并且不会清除该字段。
What am I doing wrong here? 我在这做错了什么? Shouldn't TextField work the same way as a text type input?
TextField的工作方式与文本类型输入的工作方式不一样吗?
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. 我想对于TypeScript主题,您必须公开声明您正在使用的接口。
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
但要更新它,你必须创建一个函数并在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. 将输入值分配给使用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 您可以在此处查看示例https://codepen.io/jasp402/pen/EBWBgO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.