[英]ReactJS - How can I set a value for textfield from material-ui?
I have a selectField and I want to set a value on it.我有一个 selectField,我想为其设置一个值。 Let say I type on it and when I click a button, the button will call a function that will reset the value of the textfield?
假设我在上面打字,当我点击一个按钮时,该按钮会调用一个 function 来重置文本字段的值?
<TextField hintText="Enter Name" floatingLabelText="Client Name" autoWidth={1} ref='name'/>
You can do it in this way你可以这样做
export default class MyCustomeField extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'Enter text',
};
}
handleChange = (event) => {
this.setState({
value: event.target.value,
});
};
handleClick = () => {
this.setState({
value:'',
});
};
render() {
return (
<div>
<TextField
value={this.state.value}
onChange={this.handleChange}
/>
<button onClick={this.handleClick}>Reset Text</button>
</div>
);
}
}
It's maintained that the right way is to have the component be controlled in a scenario like the accepted answer there, but you can also control the value in this gross and culturally unacceptable way.坚持认为正确的方法是在类似于那里接受的答案的场景中控制组件,但您也可以以这种粗暴且文化上不可接受的方式控制价值。
<TextField ref='name'/>
this.refs.name.getInputNode().value = 'some value, hooray'
and you can of course retrieve the value like so你当然可以像这样检索值
this.refs.name.getValue()
Instead of using ref
you should use inputRef
你应该使用
inputRef
而不是使用ref
const MyComponent = () => {
let input;
return (
<form
onSubmit={e => {
e.preventDefault();
console.log(input.value);
}}>
<TextField
hintText="Enter Name"
floatingLabelText="Client Name"
autoWidth={1}
inputRef={node => {
input = node;
}}/>
</form>
)
};
I would suggest to do a little wrap on the original MUI TextField.我建议对原始 MUI TextField 做一些包装。
export default function ValueTextField(props) {
const [value, setValue] = useState(props.value);
return (
<TextField {...props} onChange={(event) => setValue(event.target.value)} value={value}/>
);
}
Now you can use your own ValueTextField component now.现在您可以使用自己的 ValueTextField 组件了。
<ValueTextField value={"hello world"}></ValueTextField>
I prefer this way to assign the state variables:我更喜欢这种分配状态变量的方式:
<TextField value={mobileNumber}
onChange={e => { this.setState({ mobileNumber: e.target.value }) }}
className={classes.root}
fullWidth={true}
label={t('mobile number')} />
Here is a short simple React Hook version of the answer这是答案的一个简短的简单 React Hook 版本
export default function MyCustomeField({
initialValue= '',
placeholder= 'Enter your text...'
}) {
const [value, setValue] = React.useState(initialValue)
return (
<div>
<TextField
placeholder={placeholder}
value={value}
onChange={e => setValue(e.target.value)}
/>
<button onClick={() => setValue(initialValue)}>Reset Text</button>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.