我知道React.createRef()
很简单,要引用某些内容,只需在构造函数中声明:
constructor(props) {
super(props)
this.inputRef = React.createRef()
}
然后渲染:
render() {
<input ref={this.inputRef} type="text" />
}
我不知道如何在React版本16中使用Refs和DOM。
我有此列表并呈现:
<div>{arr.map(person => <div>{person.name}</div>)}
我该如何实现?
答案 0 :(得分:0)
您可以在裁判上使用其他名称
<input type="text" ref={this.inputField1} />
<input type="text" ref={this.inputField2} />
在构造函数中,您可以将createRef两者都使用,如下所示:
this.inputField1 = React.createRef();
this.inputField2 = React.createRef();
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.inputField1 = React.createRef();
this.inputField2 = React.createRef();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.inputField1.current.value = '1'
this.inputField2.current.value = '2'
}
render() {
return (
<div>
<input type="text" ref={this.inputField1} />
<input type="text" ref={this.inputField2} />
<button type="button" onClick={this.handleClick}>
click me
</button>
</div>
);
}
}
ReactDOM.render(
<MyComponent/>,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container">
</div>