仔细、细心!!!
输入造成的死循环错误
当想把return 的 GuestGreeting 和 UserGreeting 互换的时候,手动输入两个函数而不是复制粘贴。手动输入把Guest改为User,User改为Guest,当第一个改完,第二个没改完的时候,第二个函数是 xxGreeting,工具会认为是Greeting,因为 Function函数定义的是 Greeting,自己嵌套调用自己会造成死循环。
function Greeting(props) {const isLoggedIn = props.isLoggedIn;if (isLoggedIn) {return <GuestGreeting />;}return <UserGreeting />;}
=> 方法的优点和小细节
优点是可以减少绑定。
constructor(props) {super(props);this.state= {showModal: false };this.handleShow = this.handleShow.bind(this);this.handleHide = this.handleHide.bind(this);}handleShow () {this.setState({showModal: true});}handleHide() {this.setState({showModal: false});}
两个方法是等价的。
constructor(props) {super(props);this.state= {showModal: false };this.handleShow = this.handleShow.bind(this);this.handleHide = this.handleHide.bind(this);}handleShow =()=> {//函数的紫色this.setState({showModal: true});}handleHide =()=> {//平常色this.setState({showModal: false});}
小细节:当多个绑定的时候,从第二个开始,绑定的颜色不会变化,会误以为错误。不必担心
- 输入造成的错误。在 handleShow的时候,多输入了一个等号,导致一种误解:=>方法只能适用一个和 this等价的方法,不能适用多个,后来发现了这个等号,再次尝试的时候,发现 =>方法适用于多个和this等价的方法。只是从第二个开始方法的颜色不改变
constructor(props) {super(props);this.state= {showModal: false };}handleShow =()=> {this.setState=({showModal: true});//多输了一个不必要的等号}handleHide =()=> {this.setState({showModal: false});}
具体实现
class App extends React.Component{constructor(props) {super(props);this.state= {showModal: false };}handleShow =()=> {this.setState({showModal: true});}handleHide =()=> {this.setState({showModal: false});}render(){const modal=this.state.showModal ? (<Modal><div className="modal"><div>193909010330</div><br/>194106220345<button onClick={this.handleHide}>Hide Modal</button></div></Modal>):null;return(<div className="app">1933<br/><button onClick={this.handleShow}>Show Modal</button>{modal}</div>);}}ReactDOM.render(<App />,appRoot);
执行结果

构造函数
class 和function中都有构造函数,function中是默认的,class中是设置默认的初始状态,使用它的原因是render 渲染的方法有生命周期,如果没有生命周期,不需要使用构造函数
render和渲染中的return
class是原生对象,class本身不做 render 渲染,是class中 new 的方法做 render。
render中需要返回值的,即在页面中需要展现的就加return 方法,不需要的就不加return 方法。有些方法需要render,但不需要在页面展现,就不需要return。
class
class不是对象,是原生对象(抽象但,不是对象)。JS可以用 class 把一切不是对象的变成函数对象,所以一切皆对象。和数学可以形成很大的类似。数学可以把一切数据变成对象。
