props和父子组件传值
import React from "react";
// 引入 MySon 子组件
import MySon from "./MySon";
// 父组件
class App extends React.PureComponent {
state = {
mes:'你好呀'
};
render() {
return (
<div className="App">
<p>父组件</p>
{/* 可以直接这样传值 a="" 也可以这样 msg={} 传值 */}
{/* 在react props不传才显示默认值 */}
{/* 在react props不传才显示默认值 */}
{/* 类似于vue作用域插槽 scopeslot={(scope) => { return <div>{scope }</div> }}
在父组件scope接收子组件传过来的数据 进行展示
*/}
<MySon a={<span>类似于vue中的具名插槽</span>} scopeslot={(scope) => { return <div>{scope }</div> }} msg={this.state.msg}>
<div>类似于vue中的插槽</div>
</MySon>
</div>
);
}
}
export default App;
import React from "react";
// MySon 子组件
class MySon extends React.PureComponent {
state = {
somMsg: "这是作用域插槽",
};
render() {
// 直接打印this.props可以拿到父组件所有传过来的数据
console.log(this.props);
return (
<div className="MySon">
<p>
{/* this.props.msg 可以直接展示父组件传过来的值 */}
子组件:{this.props.msg}
</p>
{/* 展示 父组件过来的html元素 类似于vue中的插槽 */}
{this.props.children}
<p>类似于vue具名插槽: {this.props.a}</p>
{/* 类似于vue作用域插槽 调用父组件的方法 把子组件的数据传过去*/}
{this.props.scopeslot(this.state.somMsg) }
</div>
);
}
}
// 设置类型
MySon.propTypes = {
msg: function (props) {
// 类型验证 不是一个字符串类型,就会抛出一个错误
if (typeof props.msg !== "string") {
throw new Error("msg must be a string");
}
},
...其他类型验证
};
// 默认值 在react props不传才显示默认值
MySon.defaultProps = {
msg: "i am msg default",
...其他属性默认值
};
export default MySon;
验证方法库 proptypes 继承了很多验证方法
安装命令 `npm install proptypes --save`
//在MySon子组件 引入proptypes验证库
import proptypes from "proptypes"
// 使用proptypes设置类型
MySon.propTypes = {
msg: proptypes.string
};
父传子
{/* 父传子 msg={<span>内容</span>} msg="" */}
<MySon msg={this.state.msg} content={<span>内容</span>}>
<div>传给子组件内容</div>
</MySon>
//子组件接收
<div className="MySon">
{this.props.msg}
{this.props.content}
{this.props.children}
</div>
子传父
//子组件
<div className="MySon">
{this.props.msg}
<button onClick={() => {
this.props.changeMsg("子组件传给父组件的内容")
}}>修改</button>
</div>
//父组件
changeMsg(sonmsg) {
console.log('子组件传过来的值', sonmsg);
//会出现this 指向问题
this.setState({
msg: item
})
}
//在这里添加 .bind()可以解决this指向问题
<MySon msg={this.state.msg} changeMsg={this.changeMsg.bind(this)}></MySon>