原文博客地址: https://finget.github.io/2018/06/08/vue-react-props/
// father.js <template> <div id="father"> 这是父组件: <p>父组件</p> <Child ref="child" :msg="msg" @click="faClick"></Child> </div> </template> <script> import Child from './child'; export default { data() { return { msg: '父组件传给子组件' // 传递给子组件的值 }; }, components: { Child }, methods: { faClick(msg) { // msg 子组件传递给父组件的值 alert(msg); }, childSayHello() { // 父组件调用子组件的方法 this.$refs,child.sayHello(); } } } </script>
// child.js <template> <div id="child"> 这是子组件:<p>父组件传递的值:{{msg}}</p> <button @click="click">接收父组件方法</button> </div> </template> <script> export default { props: ['msg'], data() { return { childMsg : '哈哈哈' }; }, methods: { click() { this.$emit('click',this.childMsg); // 第一个参数为派发的事件名, 第二个参数为传递的值 }, sayHello() { alert('I am child!'); } } } </script>
props:['msg']
(不能省略引号):msg="msg"
的方法传递变量,也能够经过 msg="msg"
传递字符串ref="xxx"
属性this.$refs.xxx.方法
调用this.$emit('事件名','参数')
派发一个事件,并传递参数@事件名
的方式监听事件子组件能够经过this.$parent.xxx
直接调用父组件的方法。javascript
经过子组件派发的事件,不只能够向父组件传递参数,父组件也能够经过传递的参数,改变向子组件传递的值,从而改变子组件。
props 还能够进行一系列的格式校验,更多内容查看官网html
props: { // 基础的类型检查 (`null` 匹配任何类型) propA: Number, // 多个可能的类型 propB: [String, Number], // 必填的字符串 propC: { type: String, required: true }, // 带有默认值的数字 propD: { type: Number, default: 100 }, // 带有默认值的对象 propE: { type: Object, // 对象或数组且必定会从一个工厂函数返回默认值 default: function () { return { message: 'hello' } } }, // 自定义验证函数 propF: { validator: function (value) { // 这个值必须匹配下列字符串中的一个 return ['success', 'warning', 'danger'].indexOf(value) !== -1 } } }
// father.js import React, { Component } from 'react' import Child from './child.js'; class Father extends Component { constructor(props) { super(props); this.state = { con: '父组件给子组件' } } // 传递给子组件的方法,并接收子组件实例,绑定在this.child上 onRef = (ref) => { this.child = ref } // 经过this.child 就能够直接调用子组件的内部方法 click = () => { this.child.sayHello(); } // 传递个子组件的方法 faClick = (msg) => { alert(msg); } render() { return ( <div> <p>这是父组件</p> <button onClick={this.click}>调用子组件方法</button> <div> 这是子组件 <Child onRef={this.onRef} connect={this.state.con} click={(msg) => this.faClick(msg)}/> </div> </div> ) } } export default Father;
// child.js import React, { Component } from 'react' class Child extends Component { constructor(props) { super(props); } // 调用父组件传递的方法,并传递子组件实例 componentDidMount(){ this.props.onRef(this); } // 调用父组件传递的方法 click= ()=> { this.props.click('哈啊哈'); } // 子组件内部方法 sayHello = () => { alert('I am child'); } render() { return ( <div> <p>{this.props.connect}</p> <button onClick={this.click}>接收父组件的方法</button> </div> ) } } export default Child;
connect={this.state.con}
方式能够传递值this.props.connect
接收onRef={this.onRef}
componentDidMount
生命周期里 调用这个方法,并回传自身实例this.child = ref
this.child.xxx
直接调用子组件方法click={(msg) => this.faClick(msg)}
onClick={this.click}
click= ()=> {this.props.click('哈啊哈');}
从而传递参数this.props.xxx
调用
不能直接经过
<button onClick={this.props.click('哈啊哈')}>接收父组件的方法</button>
进行传参,这样在组件初始化时,事件就执行了。
this.props.click
能够调用父组件传递的方法,并传参