JSX
Well then how do we pass these values to a component from outside? That's where props
comes in. In React lingo, props
is something that the component is passed by the user of that component (parent component passes props
to child component).
You can pass anything as a prop: function
, object
, boolean
, string
, number
, etc. Here's an example of a Component passing the props
to its children.
```jsx
function Children(props) {
return (
<div>{props.textToDisplay}</div>
)
}
function Parent(props) {
return (
<Children textToDisplay={'Hello'}></Children>
//实际就是把'Hello'这个传进去,传给textToDisplay这个
//变量给Children然后Children就返回一个<div>这个属性。
)
}
There are couple things going on here. First - remember on the first page of this tutorial we said that we can compose components (we can use one component inside the other)? Well that's what we are doing here. Parent
component uses Children
component inside it's return.
There are couple things going on here.
First - remember on the [first page of this tutorial] we said that we can compose components (we can use one component inside the other)? Well that's what we are doing here. Parent
component uses Children
component inside it's return.
Second - if you inspect the above code snippet carefully, we see that when the Parent
uses the Children
(inside return
) it's also passing something called textToDisplay
with some value Hello
. We call this "passing the props". So Parent
is passing a props
called textToDisplay
to the Children
. How, then, does the Children
use the value that the Parent
passes down to it?
-
Component created with function
If you created your component as a
function
like we did here, all theprops
itsParent
passed down will be accessible through the argument. If you look at theChildren
above it's usingprops.textToDisplay
inside thediv
. All theprops
passed to theChildren
are passed as this singleprops
argument. For example, if theParent
had passed a props calleddefaultValue
, theChildren
would access it asprops.defaultValue
. -
Component created as React.Component
If you created your Component by extending
React.Component
then all theprops
would be available asthis.props
. The equivalent of aboveChildren
function usingReact.Component
would look like this:
class Children extends React.Component {
render(){
return (
<div>{this.props.textToDisplay}</div>
)
}
}