[React] Use React ref to Get a Reference to Specific Components
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[React] Use React ref to Get a Reference to Specific Components相关的知识,希望对你有一定的参考价值。
When you are using React components you need to be able to access specific references to individual component instances. This is done by defining a ref
. This lesson will introduce us to some of the nuances when using ref
.
<input ref="b" type="text" onChange={this.update.bind(this)} />
The way to refer to the ‘ref‘:
this.refs.b.value
Also ‘ref‘ is able to receive a callback function:
<Input ref={ component => this.a = component} update={this.update.bind(this)} /> class Input extends React.Component { render(){ return <div><input ref="input" type="text" onChange={this.props.update}/></div> } }
Now the way to access the ref value:
this.a.refs.input.value,
class App extends React.Component { constructor(){ super(); this.state = {a: ‘‘, b: ‘‘} } update(){ this.setState({ a: this.a.refs.input.value, b: this.refs.b.value }) } render(){ return ( <div> <Input ref={ component => this.a = component} update={this.update.bind(this)} /> {this.state.a} <hr /> <input ref="b" type="text" onChange={this.update.bind(this)} /> {this.state.b} </div> ) } } class Input extends React.Component { render(){ return <div><input ref="input" type="text" onChange={this.props.update}/></div> } } ReactDOM.render( <App />, document.getElementById(‘root‘) );
以上是关于[React] Use React ref to Get a Reference to Specific Components的主要内容,如果未能解决你的问题,请参考以下文章
[React] Use React.cloneElement to Modify and Add Additional Properties to React Children
[React] Use React Context to Manage Application State Through Routes
[React] Use React Fragments to make your DOM tree cleaner
[React + GraphQL] Use useLazyQuery to manually execute a query with Apollo React Hooks
[React] Refactor a connected Redux component to use Unstated