简体   繁体   English

ReactJS - 如何为 material-ui 的文本字段设置值?

[英]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.

相关问题 如何居中对齐 Material-ui TextField 文本并设置最小数值? - How can I center-align Material-ui TextField text and also set a min number value? 如何在 material-ui 中为当前日期和时间的文本字段类型 datetime-local 设置默认值? - how can I set the default value to the textfield type datetime-local in material-ui for the current date and time? 如何在 Material-UI TextField 中设置当前日期 - How Do I Set The Current Date In A Material-UI TextField ReactJS + Material-UI:如何使用 Material-UI 将当前日期设置为默认值<DatePicker> ? - ReactJS + Material-UI: How to set current date as default value using Material-UI's <DatePicker>? 如何在 ReactJS 中设置或清除 material-ui Input 的值 - How to set or clear value of material-ui Input in ReactJS 如何突出显示 material-ui TextField 中的部分文本 - How can I highlight part of the text in material-ui TextField 如何屏蔽我的 Material-UI TextField? - How Can I Mask My Material-UI TextField? 如何将 material-ui TextField 设置为仅接受十六进制字符 - How can I set material-ui TextField to accept only Hexidecimal characters 如何设置类似于 Material-UI 的轮廓文本字段的 static 轮廓 div? - How can I set an static outlined div similar to Material-UI's outlined textfield? 在Material-UI TextField中,当输入模糊时,如何防止标签落在装饰物后面? - In a Material-UI TextField how can I prevent a label from falling behind an adornment when the input is blurred?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM