JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

React Tutorial - Transferring Props

Author:JIYIK Last Updated:2025/03/15 Views:

In React , a very common pattern is to abstract and encapsulate components. These components will expose some properties (Props) to perform some simple functions, but their internal details may be more complicated. In general, Props are unchanged. Here is how to use them:

{this.props.key}

Let's first use a piece of code to see how Props is used

var CommentBox = React.createClass({
        render:function(){
            return (
                <div className="CommentBox">
                    Hello, world! I am a {this.props.name}.
                </div>
            );
        }
    }
);
ReactDOM.render(
    <CommentBox name="Props" />,
    document.getElementById('content')
);

See, it's actually that simple to use Props. From the above example, we can see that Props can actually be seen as a way to communicate between components. Of course, the communication between components will be introduced later. Here we only introduce the transfer of Props - Transferring Props .

Okay, let's continue looking at the following code

var Checkbox = React.createClass({
    render: function() {
        var Cbox = this.props.checked ? 'Checked' : 'Unchecked';
        return (
            <div className={Cbox} >
                {this.props.children}
            </div>
        );
    }
});
ReactDOM.render(
    <Checkbox checked={true}>
        Hello world!
    </Checkbox >,
    document.getElementById('content')
);

There is nothing wrong with this code. However, if I want to add attributes such as title, name, onClick, etc. to the div tag, do I need to write each one in the component?

<div className={fancyClass} onClick={this.props.onClick} name={this.props.name} title={this.props.title}>
    {this.props.children}
</div>

This is obviously very verbose and unsafe. We can solve this problem by using the JSX feature… Its function is to extract unknown attributes.

Its usage is to list the attributes to be used currently, followed by ...other (Note: the string following ... is not fixed to be other, it can also be other, for example: onmpw).

var {checked, ...other} = this.props;

This ensures that all props except those explicitly used are passed down. At this time, ...other stores all properties except the checked property. For the above example, we can rewrite it as follows

var Checkbox = React.createClass({
    render: function() {
         var {checked , ...other} = this.props;
        var  Cbox = checked ? 'Checked' : 'Unchecked';
        return (
            <div className={Cbox} {...other} />
        );
    }
});
ReactDOM.render(
    <Checkbox checked={true} title="迹忆博客" name="onmpw">
        Hello world!
    </Checkbox >,
    document.getElementById('content')
);

在这个例子中,…other 中的属性为title、name和children,没有checked。

var {checked,title , ...other} = this.props;

这样,在 ...other 中的属性为name和children,就也不包含title了。

下面我们介绍一个和…other 类似的知识点,就是 …this.props。看下面的例子:

var Checkbox = React.createClass({
    render: function() {
        var  Cbox = this.props.checked ? 'Checked' : 'Unchecked';
        return (
            <div className={Cbox} {...this.props} />
        );
    }
});

其实,这里…this.props和…other功能差不多。但是,其不同的地方在于,…other是包含除了明确使用的属性以外剩下的那些属性。而…this.props包含所有的属性,不论你是否是明确使用的。也就是说,在上面的额例子中,checked属性也会被传到组件里面去。

如果一个属相被使用了,但是还想接着往下传那应该怎么办。我们通过上面的讲解知道,如果使用…other方式的话,属性被使用了就无法再往下传了。所以说如果想要往下继续传递的话,可以使用checked={checked}这种方式再次重传。

看下面的例子

var Checkbox  = React.createClass({
    handleChange:function(){
        console.log('迹忆博客');
    },
    render: function() {
        var { checked, title, ...other } = this.props;
        var Cbox = checked ? 'FancyChecked' : 'FancyUnchecked';
        var boxTitle = checked ? 'Y ' + title : 'N ' + title;
        return (
            <label>
                <input {...other}
                    checked={checked}
                    className={Cbox}
                    type="checkbox"
                    onChange={this.handleChange}
                 />
                {boxTitle}
            </label>
        );
    }
});
ReactDOM.render(
    <Checkbox  checked={true} name="onmpw" title="迹忆博客" />,
    document.getElementById('content')
);

这里我们要注意属性的顺序。我们把input中{…other}放在JSX Props的前面是保证JSX的Props不被覆盖。在上面的例子中我们就可以保证input的类型就是checkbox。

比方说吧,如果我们input中的Props的顺序是下面这样的

<input
    type="checkbox"
    {...other}
    checked={checked}
    className={Cbox}
    onChange={this.handleChange}
    />

而我们又在使用render渲染的时候指定了input的type属性为text

<Checkbox type="text" checked={true} name="onmpw" title="Ji Yi Blog" />

What you end up with is not a checkbox, but an input box, because the type="checkbox" attribute of input is overwritten by the type attribute in ...other.

Well, I believe that everyone has a clearer understanding of the concept of React Props and the transmission of Props. I hope this article will be helpful for everyone to learn React.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Rendered fewer hooks than expected error in React

Publish Date:2025/03/16 Views:50 Category:React

When we use a hook after a condition that may return a value, we get the error "Rendered fewer hooks than expected. This may be caused by an accidental early return statement". To fix this error, you need to move all React hooks to any condition that

Fix Uncaught ReferenceError: useState is not defined in React

Publish Date:2025/03/15 Views:142 Category:React

When we use the useState hook in our code but forget to import it, it generates the error Uncaught ReferenceError: useState is not defined. To fix this error, you need to import the hook before using it import {useState} from react . // ?️

React error Uncaught ReferenceError: process is not defined solution

Publish Date:2025/03/15 Views:117 Category:React

To resolve the “Uncaught ReferenceError: process is not defined” error in React, open a terminal in the root directory of your project and update the version of the `react-scripts` package by running `npm install react-scripts@latest` and reinstal

React Error Property 'X' does not exist on type 'Readonly<{}>'

Publish Date:2025/03/15 Views:140 Category:React

The React.js error “Property does not exist on type 'Readonly'” occurs when we try to access the props or state of an untyped class component. To fix the error, you need to use generics on the React.Component class to type the props or state of th

Fix the value prop on input should not be null error in React

Publish Date:2025/03/15 Views:142 Category:React

The warning "value prop on input should not be null" is caused when we set the initial value of an input to null or override the initial value setting it to null, e.g. from an empty API response. Use a fallback value to solve this problem.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial