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

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.

主站蜘蛛池模板: 宣威市| 明水县| 靖州| 合山市| 仪征市| 花莲县| 辽阳市| 苗栗县| 石首市| 芒康县| 苏尼特左旗| 望奎县| 望奎县| 石城县| 仁布县| 西乡县| 姚安县| 林芝县| 罗江县| 谢通门县| 吉木萨尔县| 海淀区| 晋州市| 隆子县| 台江县| 桃源县| 丹巴县| 昂仁县| 新蔡县| 阜宁县| 张家口市| 桓仁| 长武县| 台山市| 靖江市| 仁布县| 广元市| 明光市| 克拉玛依市| 和静县| 吉安县|