我正在构建一个小聊天应用程序。我使用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库?
在onChange方法中,您不需要使用ref
来访问相同textfield的值,在onChange方法中使用material-ui TextField传递2个参数:
event, value
所以你可以这样写它而不使用ref:
<TextField ... onChange={(e, value) => this.handleChanges(value) }/>
根据DOC:
onChange:功能
文本字段值更改时触发的回调函数。
签名:function(event:object,newValue:string)=> void
事件:更改定位文本字段的事件。
newValue:文本字段的新值。
你也可以使用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更改让你在更改时更新状态,但是如果你需要保持值不变,那么inputRef是必要的。
另外看看你可以看到这个How to get password field value in react's material-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这样的事情。
此解决方案允许多个TextField元素,可由此类(名称)访问,可在类中访问。
我们仍然可以使用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>
}