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

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.

主站蜘蛛池模板: 固始县| 江源县| 肇源县| 鄯善县| 松阳县| 望江县| 隆安县| 农安县| 岑巩县| 娱乐| 英山县| 棋牌| 青田县| 阳西县| 马边| 兰西县| 马鞍山市| 万山特区| 赤峰市| 姜堰市| 东阳市| 岐山县| 东阳市| 博野县| 鲜城| 澎湖县| 兴宁市| 老河口市| 汪清县| 房产| 腾冲县| 衡水市| 墨玉县| 上蔡县| 黑龙江省| 毕节市| 湾仔区| 长岭县| 安吉县| 福清市| 黄陵县|