Material UI 组件引用不起作用

Material UI component reference does not work

我正在建立一个小聊天室 application.i 已经使用 Material UI TextField 来输入用户消息。但我不能参考它。我读到了这个。他们说他们不支持refs。 这是我的代码。并且有效。

class App extends Component {
  constructor() {
    super();
    this.state = {
      q: "default"
    };

  }
  handleChanges(val) {
    this.setState({ q: val });
  }
  handleSearch(val) {
    this.setState({ q: val });
    console.log(this.state.q);
  }
  render() {
    return (
      <div className="App">
        <h1>  {this.state.q}</h1>
        <Row className="show-grid">
          <Col sm={2} md={4} className="contact"><h5>contact</h5><br /></Col>
          <Col sm={10} md={8} className="chat grid-border"><h5>chat</h5><br />
            <div className="history"></div>
            <div className="message top-border">

              <input type="text" ref="question" onChange={(e) => { this.handleChanges(this.refs.question.value) }} />
              <MuiThemeProvider>
                <FlatButton label="Primary" primary={true} onTouchTap={(e) => { e.preventDefault(); this.handleSearch(this.refs.question.value); }} />
              </MuiThemeProvider>

            </div>
          </Col>
        </Row>{/*show-grid ends here*/}
      </div>
    );
  }
}
export default App;

如果我使用这个 material UI TextField 而不是原生 HTML 输入标签,它不会从引用中获取值。

<MuiThemeProvider>
       <TextField hintText="Ask your question" fullWidth={true} multiLine={true} rows={2} rowsMax={4} type="text" ref="question" onChange={(e) => { this.handleChanges(this.refs.question.value) }}/>
</MuiThemeProvider> 

是否有任何解决方法或替代 UI 库?

这种引用元素的方式已被弃用。参见 https://facebook.github.io/react/docs/refs-and-the-dom.html

试试这个:

<TextField hintText="Ask your question" fullWidth={true} multiLine={true} rows={2} rowsMax={4} type="text" ref={(input) => { this.input = input; }} onChange={(e) => { this.handleChanges(this.refs.question.value) }}/>

并将 TextField 引用为 this.input

如果要获取 TextField 值,请使用 this.input.getValue()

我做了类似的事情here

在 onChange 方法中,您不需要使用 ref 来访问同一个文本字段的值,material-ui TextField 在 onChange 方法中传递 2 个参数:

event, value

所以不用ref也可以这样写:

<TextField ... onChange={(e, value) =>  this.handleChanges(value) }/>

根据DOC

onChange: function

Callback function that is fired when the textfield's value changes.

Signature: function(event: object, newValue: string) => void

event: Change event targeting the text field.

newValue: The new value of the text field.

您也可以使用inputRef。此道具可从 material 1.0.

获得
<TextField
   className={classes.textField}
   inputRef={input => (this._my_field = input)}
   label="My field"
   fullWidth
   margin="normal"
   defaultValue={this.props.my_field}
   onChange={this.handleChange("dhis_password")}
/>

on change 可以让你在状态发生变化时更新状态,但如果你需要获取不变的值,那么 inputRef 是必需的。

也看看你可以看到这个

此解决方案允许多个 TextField 元素,可通过 class.

中的 this.(name) 访问。

我们仍然可以使用 ref,但必须传入一个函数并在 class 上添加另一个 属性(不是在 props、refs 或 state 上,而是在 class 本身)。 Material UI 提供了一个 .getValue() 方法,我们可以从中检索值。

class App extends Component {
...
handleQuestion() {
    this.setState({
        q : this.question.getValue(),
        /** add more key/value pairs for more inputs in same way **/
    })
}
...
<MuiThemeProvider>
   <TextField 
      hintText="Ask your question"
      fullWidth={true} 
      multiLine={true} 
      rows={2} 
      rowsMax={4} 
      type="text" 
      ref={(q) => { this.question = q; }}
      onChange={ this.handleQuestion }
    />
</MuiThemeProvider> 



}

如果你使用无状态功能组件 material ui 那么你可以使用 React hooks。

import React, { useState, useRef } from "react";

let MyComponent = (props) => {

  let textInput = useRef(null);

  return (
    <div>
      <Button
        onClick={() => {
          setTimeout(() => {
            textInput.current.focus();
            textInput.current.click();
            textInput.current.value="myname";
          }, 100);
        }}
      >
        Focus TextField
      </Button>
      <TextField
        fullWidth
        required
        inputRef={textInput}
        name="firstName"
        type="text"
        placeholder="Enter Your First Name"
        label="First Name"
      />
    </div>
  );
};

尝试以下方法

    let emailRef =React.createRef();

在 material-ui 输入字段中使用 inputRef

 <TextField label="Email Address" name="email" inputRef ={emailRef} />

只需使用 inputRef 而不是 ref