main idea
- Component defines a parent
this.state.focus=false
incoming subassembly, this subassembly acquisition parameters to determine whether to perform props.fosus focus () - By clicking the button
this.setState
to change the focus, at this time will trigger render redraw, sub-assemblies obtained props.focus been updated so that the focus execution;
here I encountered a problem
I defined a proprietary method Son assembly isFocus
then render the implementation of this method, the results did not achieve the desired results.
the reason
isFocus execution time before the render, sovar a = document.createElement('input')
execution, had not this element, the element that is not acquired; it is necessary to perform this sentence before the fishes in the dom tree.
In summary
isFocus defined componentDidUpdate which fishes; because, although the first performance is componentDidMount, but this time the initialization state, not necessary to obtain the element, and render redrawn after each, then componentDidUpdate been performed on dom tree, elements can be obtained.
Father.js
import React from "react"
import {render} from "react-dom"
import Son from "./Son.js"
class Father extends React.Component{
constructor(){
super();
this.state={
'focus':false
};
console.log("Father Constructor")
}
click(){
this.setState({
'focus':true
});
}
render() {
return(
<div>
<input type="button" value='父组件' onClick={(this.click).bind(this)} />
<Son focus={this.state.focus}/>
</div>
)
}
}
export default Father
Son.js
import React from "react"
import {render} from "react-dom"
class Son extends React.Component{
constructor({focus}){
super();
}
componentDidUpdate(prevProps, prevState, snapshot) {
var self = this;
var a= document.getElementById('input');
!function isFocus(){
if (self.props.focus){
a.focus()
}
}()
}
render() {
return(
<div>
<input type="text" value='' ref='a' id='input'/>
</div>
)
}
}
export default Son
to sum up
This as a template can be: when the parent component subassemblies require intervention, may be passed to a variable, and then through the sub-assembly this.props.val
to judge whether an operation