【问题标题】:Material UI component reference does not workMaterial UI 组件参考不起作用
【发布时间】:2017-10-13 02:22:21
【问题描述】:

我正在构建一个小聊天应用程序。我使用 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;

如果我使用此材质 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 库?

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    您也可以使用inputRef。此道具可从材料 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 让你在 state 改变时更新它,但是如果你需要保持 value 不变,那么 inputRef 是必要的。

    也看看你可以看到这个How to get password field value in react's material-ui

    【讨论】:

      【解决方案2】:

      试试下面的

          let emailRef =React.createRef();
      

      在material-ui输入栏使用inputRef

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

      只使用inputRef 而不是参考

      【讨论】:

        【解决方案3】:

        这种引用元素的方式已被弃用。见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

        【讨论】:

        • 它有效,可能与您的代码有关。你能分享你的代码吗?
        • 嗨,Adrian,您使用的是 Class 元素还是 Pure 元素?你能分享一些小提琴吗?
        【解决方案4】:

        如果您正在使用带有材质 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>
          );
        };
        

        【讨论】:

          【解决方案5】:

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

          event, value
          

          所以你可以这样写而不使用 ref:

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

          根据DOC

          onChange: 函数

          文本字段值更改时触发的回调函数。

          签名:函数(事件:对象,新值:字符串)=> void

          事件: 更改针对文本字段的事件。

          newValue: 的新值 文本字段。

          【讨论】:

          • 很好的解决方案。如果我们添加另一个 元素,相同的方法将不起作用。需要编写一个重复的方法。理想情况下,使用 refs,给定 2 个 TextField 上的 ref="a" 和 ref="b",我们可以在 setState 方法中检查 this.refs.a.value 和 this.refs.b.value,但这不起作用使用 Material UI。
          【解决方案6】:

          此解决方案允许多个 TextField 元素,可通过类内部的 this.(name) 访问。

          我们仍然可以使用 ref,但必须通过传入一个函数并在类上添加另一个属性(不是在 props、refs 或 state 上,而是在类本身上)。 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> 
          
          
          
          }
          

          【讨论】:

            猜你喜欢
            • 2016-12-26
            • 2016-06-15
            • 2022-01-09
            • 2020-09-11
            • 2022-11-25
            • 2015-09-26
            • 2022-10-31
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多