Javascript

ReactNative Day4

本文主要是介绍ReactNative Day4,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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?

  1. Component created with function

    If you created your component as a function like we did here, all the props its Parent passed down will be accessible through the argument. If you look at the Children above it's using props.textToDisplay inside the div. All the props passed to the Children are passed as this single props argument. For example, if the Parent had passed a props called defaultValue, the Children would access it as props.defaultValue.

  2. Component created as React.Component

    If you created your Component by extending React.Component then all the props would be available as this.props. The equivalent of above Children function using React.Component would look like this:

class Children extends React.Component {
    render(){
        return (
            <div>{this.props.textToDisplay}</div>
        )
    }
}
这篇关于ReactNative Day4的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!