×
  • 反应– The Complete Guide (incl. 反应Router 4 & Redux)

  • 13 –了解使用状态

    课程清单

    In the last lesson, we had a look on props. props simply an object giving us access to all the attributes we pass to our own components.
    现在,有时您不想从外部获取一些信息,但希望将其包含在组件内部并从内部进行更改。
    例如在我们的 App.js 假设我们还想要一个按钮,如果单击该按钮,只需切换一个我们在其中使用的名称

    src / App.js
    
    import React, { Component } from 'react';
    import './App.css';
    import Person from './Person/Person';
    class App extends Component {
    	render() {
    		return (
    			<div className="App">
    				<h1> Heading</h1>
    				<button>Switch Name</button>
    				<Person name="露西" age="23" />
    				<Person name="Max" age="12">
    					My Hobbies : Dancing
    				</Person>
    				<Person name="Mike" age="34" />
    			</div>
    		);
    	}
    }
    export 默认 App;
    
    在接下来的讲座中,我们将处理单击事件。

    但首先我们需要定义属性名称(在 App.js > Person component) in a non hardcoded way. Right now we have hardcoded into our JSX code and that is ok, But if we want to change it we have to store in some variable or something like that.
    现在,在课堂上我们可以定义将在该垂直组件内部使用的变量

    src / App.js
    
    import React, { Component } from 'react';
    import './App.css';
    import Person from './Person/Person';
    class App extends Component {
    	 state = {
    		 persons: [
    		 	{name: 'Lucy', age: 23},
    		 	{name: 'Max', age: 12},
    	 		{name: 'Mike', age: 34},
    		 ]
    	 }
    	 ...
    }
    export 默认 App;
    

    the declared data is the state, we can now access a property like state and that is not just true but for any property in our render() method by simplying outputting something dynamic wit single curly braces …

    src / App.js
    
    ...
    class App extends Component {
    	state = {
    		persons: [{ name: 'Lucy', age: 23 }, { name: 'Max', age: 12 }, { name: 'Mike', age: 34 }],
    	};
    	render() {
    		return (
    			<div className="App">
    				<h1> Heading</h1>
    				<button>Switch Name</button>
    			<Person name={this.state.persons[0].name} age={this.state.persons[0].age} />  {/* this. reffers to this class */}
    				{/* goes on till number of persons in array*/}
    			</div>
    		);
    	}
    }
    export 默认 App;
    

    if you run the application in the browser you will see a new button which does nothing and you will see the data is been output with the state variable which we declare in class. As I said state would be a special property. thus the far way we don’t use in a special way through we can change this. the state can be changed and if it changes and that is the special thing about it and it only works on that state property. if it changes it will lead react to re-render our DOM or to update the DOM I should say.
    因此,如果我们更改名称 露西 例如,如果这将导致该渲染被重新渲染。我们将在下一课中看到单击事件以单击更改状态的按钮。

    反应introduction
    反应Component
    使用状态
  • 启用通知    不用了,谢谢