官术网_书友最值得收藏!

Introducing props

So, what are props? Props are shorthand for properties, and as you can guess, they define properties inside of our React components. Generally speaking, these get passed in from the parent, although they can get passed in from anywhere, truth be told.

Right now, we're just using a simple functional component, and that function doesn't specify any arguments as part of its signature, so if we want to start using props we'll have to change that first.

Let's open up our Todo component in src/Todo.js, and change the function declaration to also pass in a props argument:

const Todo = props => {

This would roughly be the equivalent of us writing the following in vanilla JavaScript:

function Todo(props) {

Next, we'll have to change the display text to actually use something from our props argument, so we'll add a reference to {props.description}:

const Todo = props => <div className="Todo">{props.description}</div>;

Save the file, because now we'll have to head back over to our primary App component (src/App.js) and start passing in the description as part of the properties passed in to our Todo components:

const App = () => (
<div className="App">
<h2>Todoifier</h2>
<br />
<Todo description="Do the thing" />
<Todo description="Do another thing" />
</div>
);

After saving the file and seeing the browser window refresh, we should expect to see the properties we just entered now show up in the browser, as follows:

And there we are! Reusable, modifiable components, done with almost no effort at all!

The even better part is that any changes to props will trigger React to re-render that component (depending on what changed and where it changed). This is something that is profoundly useful, especially when you factor in that the old world had you checking for changes, and then trying to either delete and recreate elements on the fly or try to sneak the changes in without having to remove it all away.

Props are great, overall, but if we want to do something a little more permanent and something that is better for storing how something changes over time, we need to introduce the concept of state. Instead of props, state is meant to be used for something that is changing all of the time, generally local to a single component; you'll pass the state down to child components that need it via props.

The trouble is that we're currently using functional components, which is fine for now, but the minute we want to start tracking any sort of internal state, we'll need to switch to a different method of creating our React components.

主站蜘蛛池模板: 焦作市| 尤溪县| 墨玉县| 津南区| 常德市| 安塞县| 白城市| 汕头市| 云南省| 礼泉县| 金昌市| 滁州市| 屯门区| 屏南县| 钦州市| 隆德县| 额济纳旗| 怀集县| 洛川县| 琼结县| 泰和县| 喜德县| 浪卡子县| 化德县| 肃北| 三原县| 柯坪县| 子洲县| 福海县| 广安市| 巩义市| 平顺县| 灵台县| 永善县| 金山区| 武冈市| 遂昌县| 安徽省| 瑞丽市| 梁山县| 锦州市|