父组件向子组件传值**
使用组件属性的形式父组件给子组件传值。 比如我们在<FatherItem>
组件中加入 content
属性,然后给属性传递{item}
。
<FatherItem content={item} />
传过去之后,通过this.props.xxx
的形式接收,比如:
import React, { Component } from 'react';
class FatherItem extends Component {
render() {
return (
<div> {this.props.content} </div>
);
}
}
子组件向父组件传递数据
通过事件进行传值。
//父组件
import React, { Component } from 'react';
import Child from './Child';
class Dad extends Component {
constructor(porps) {
super(props);
}
dadFn = () => {
console.log('我是父组件中的方法');
}
render() {
return (
<div>
<Child dadFn={this.dadFn}></Child>
</div>
);
}
}
export default Dad;
//子组件
import React, { Component } from 'react';
class Child extends Component {
constuctor(props) {
super(props);
}
render() {
return (
<div>
<button onClick={this.props.dadFn}>在子组件中调用父组件的方法</button>
</div>
);
}
}
子组件向父组件传值
//父组件
import React, { Component } from 'react';
import Child from './Child';
class Dad extends Component {
constructor(porps) {
super(props);
this.state = {
txt: '我是父组件'
}
}
fn = (data) => {
this.setState({
txt: data
})
}
render() {
return (
<div>
<Child cfn={this.fn}></Child>
<p>{this.state.txt}</p>
</div>
);
}
}
export default Dad;
//子组件
import React, { Component } from 'react';
class Child extends Component {
constuctor(props) {
super(props);
}
fn = (data) = {
this.props.cfn(data);
}
render() {
return (
<div>
<button onClick={()=>this.fn('我是子组件')}>子组件向父组件传值</button>
</div>
);
}
}
父组件调用子组件中的方法
//父组件
import React, { Component } from 'react';
import Child from './Child';
class Dad extends Component {
constructor(porps) {
super(props);
this.state = {
arr: ['你好', '他好'],
txt: '我是父组件'
}
}
onRef = (ref) => {
this.Child = ref;
}
chick = () => {
this.Child.childFn();
}
render() {
return (
<div>
<Child cfn={this.onRef}></Child>
<button onChick={this.click}>父组件调用子组件中的方法</button>
</div>
);
}
}
export default Dad;
//子组件
import React, { Component } from 'react';
class Child extends Component {
constuctor(props) {
super(props);
}
componentDidMount() {
this.props.onRef(this);
}
childFn = () = {
console.log('我是子组件中的方法');
}
render() {
return (
<div>
</div>
);
}
}