This is the 19th day of my participation in the August More Text Challenge

core idea

  • The parent component defines onethis.state.focus=falsePass in the child component, which gets this parameter via props. Fosus to determine whether to focus()
  • Click the button to passthis.setStateTo change focus, the render redraw is triggered, and the props. Focus obtained by the child component is updated so that focus executes.Here I have a problemI define a private method isFocus! In the Son component.

This method is then executed in Render and does not work as expected. Var a = document.createElement(‘input’); var a = document.createElement(‘input’); So it is true that this statement must be executed after dom rendering. To sum up: isFocus is defined in componentDidUpdate. For the first time, componentDidMount is initialized, so you don’t need to get the element. For every render redraw, you need to get the element after componentDidUpdate.

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= "parent" onClick={(this.click).bind(this)} /> <Son focus={this.state.focus}/> </div> ) } } export default FatherCopy the code

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 SonCopy the code

conclusion

Think of this as a template: when a parent component needs to intervene on a child component, it passes a variable, and the child component checks whether to perform the operation using this.props. Val

There is a danger that a component will not rely too much on props, but it is obvious that this component relies too much on the state provided by the parent element. So we need to do a better job of thinking about feasibility