React Tutorial - Transferring Props
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.
Related Articles
How to avoid cross-origin (CORS) issues in React/Next.js
Publish Date:2025/03/17 Views:170 Category:NETWORK
-
In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:187 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:102 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:172 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:153 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:60 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:191 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:78 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:90 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap