父组件向子组件传值**

使用组件属性的形式父组件给子组件传值。 比如我们在<FatherItem>组件中加入 content 属性,然后给属性传递{item}

  1. <FatherItem content={item} />

传过去之后,通过this.props.xxx的形式接收,比如:

  1. import React, { Component } from 'react';
  2. class FatherItem extends Component {
  3. render() {
  4. return (
  5. <div> {this.props.content} </div>
  6. );
  7. }
  8. }

子组件向父组件传递数据

通过事件进行传值。

  1. //父组件
  2. import React, { Component } from 'react';
  3. import Child from './Child';
  4. class Dad extends Component {
  5. constructor(porps) {
  6. super(props);
  7. }
  8. dadFn = () => {
  9. console.log('我是父组件中的方法');
  10. }
  11. render() {
  12. return (
  13. <div>
  14. <Child dadFn={this.dadFn}></Child>
  15. </div>
  16. );
  17. }
  18. }
  19. export default Dad;
  1. //子组件
  2. import React, { Component } from 'react';
  3. class Child extends Component {
  4. constuctor(props) {
  5. super(props);
  6. }
  7. render() {
  8. return (
  9. <div>
  10. <button onClick={this.props.dadFn}>在子组件中调用父组件的方法</button>
  11. </div>
  12. );
  13. }
  14. }


子组件向父组件传值

  1. //父组件
  2. import React, { Component } from 'react';
  3. import Child from './Child';
  4. class Dad extends Component {
  5. constructor(porps) {
  6. super(props);
  7. this.state = {
  8. txt: '我是父组件'
  9. }
  10. }
  11. fn = (data) => {
  12. this.setState({
  13. txt: data
  14. })
  15. }
  16. render() {
  17. return (
  18. <div>
  19. <Child cfn={this.fn}></Child>
  20. <p>{this.state.txt}</p>
  21. </div>
  22. );
  23. }
  24. }
  25. export default Dad;
  1. //子组件
  2. import React, { Component } from 'react';
  3. class Child extends Component {
  4. constuctor(props) {
  5. super(props);
  6. }
  7. fn = (data) = {
  8. this.props.cfn(data);
  9. }
  10. render() {
  11. return (
  12. <div>
  13. <button onClick={()=>this.fn('我是子组件')}>子组件向父组件传值</button>
  14. </div>
  15. );
  16. }
  17. }

父组件调用子组件中的方法

  1. //父组件
  2. import React, { Component } from 'react';
  3. import Child from './Child';
  4. class Dad extends Component {
  5. constructor(porps) {
  6. super(props);
  7. this.state = {
  8. arr: ['你好', '他好'],
  9. txt '我是父组件'
  10. }
  11. }
  12. onRef = (ref) => {
  13. this.Child = ref;
  14. }
  15. chick = () => {
  16. this.Child.childFn();
  17. }
  18. render() {
  19. return (
  20. <div>
  21. <Child cfn={this.onRef}></Child>
  22. <button onChick={this.click}>父组件调用子组件中的方法</button>
  23. </div>
  24. );
  25. }
  26. }
  27. export default Dad;
  1. //子组件
  2. import React, { Component } from 'react';
  3. class Child extends Component {
  4. constuctor(props) {
  5. super(props);
  6. }
  7. componentDidMount() {
  8. this.props.onRef(this);
  9. }
  10. childFn = () = {
  11. console.log('我是子组件中的方法');
  12. }
  13. render() {
  14. return (
  15. <div>
  16. </div>
  17. );
  18. }
  19. }