官网上是这么解释的:When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object “props”. 意思为: 当React看到表示用户定义组件的元素时,它会将JSX属性作为单个对象传递给此组件。我们称这个对象为“props。
顾名思义,props就是属性的简写,是单个值,是在父组件中定义或已经在state中的值,并将这些值传递给其子组件。props本身不可变,但可以通过触发state的变化,反过来改变props本身的值。
作用:用于接收组件外部的数据 传递数据: 通过给组件标签添加属性 接收数据:函数组件通过 参数 props接收数据,类组件通过 this.props接收数据
1,子组件调用父组件的方法
(1)子组件要拿到父组件的属性,需要通过 this.props
方法。
(2)同样地,如果子组件想要调用父组件的方法,只需父组件把要被调用的方法以属性的方式放在子组件上,
子组件内部便可以通过“this.props.被调用的方法
”这样的方式来获取父组件传过来的方法。
2,父组件调用子组件的方法
在 ReactJS 中有个叫 ref 的属性。这个属性就像给组件起个引用名字一样,子组件被设置为 ref 之后(比如 ref=“xxx”)。父组件便可以通过 this.refs.xxx
来获取到子组件了。
import React, { Component, Fragment } from "react";
//React的props传参
// 父组件
class App extends Component {
render() {
return (
<Fragment>
<Child name="卡卡罗特"></Child>
</Fragment>
);
}
}
// 子组件
class Child extends Component {
render() {
return <div>{this.props.name}</div>;
}
}
export default App;
运行结果
import React, { Component, Fragment } from "react";
//React的props传参
// 父组件
class App extends Component {
render() {
return (
<Fragment>
<Child name="卡卡罗特" jineng={this.bianshen}></Child>
</Fragment>
);
}
bianshen() {
return "变身超级赛亚人";
}
}
// 子组件
class Child extends Component {
render() {
return (
<div>
{this.props.name}
{this.props.jineng()}
</div>
);
}
}
export default App;
运行结果
<script type="text/babel">
//props基本使用
function ShowSaiyaren(props){
return (
<div>赛亚人有:{props.a} ---{props.b}</div>
)
}
//使用对象进行传递多个数据
let saiyaren={
a:"卡卡罗特",
b:"贝吉塔"
}
ReactDOM.render(<ShowSaiyaren{...saiyaren} />,document.getElementById("demoReact"));
</script>
运行结果
组件无论是使用函数声明还是通过 class 声明,都决不能修改自身的 props
正常情况下 props 的拥有权不属于当前组件,是别人传给你的,你用的时候用 props 来引用,所以修改的权限应该由上面来决定。
文章内容如有错误,请以官方文档为准
最后想说,文章借鉴了很多大佬的思路,非常感谢大佬们的无私共享!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。