在 React 中,父组件可以通过属性(props)向子组件传递值,子组件可以通过 this.props 获取这些值。

例如,在父组件中定义一个状态 count,并将其传递给子组件 Counter:

import React, { Component } from 'react';
import Counter from './Counter';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      <div>
        <Counter count={this.state.count} />
      </div>
    );
  }
}

export default App;

在子组件 Counter 中,可以通过 this.props.count 获取父组件传递的值:

import React, { Component } from 'react';

class Counter extends Component {
  render() {
    return (
      <div>
        <p>Count: {this.props.count}</p>
      </div>
    );
  }
}

export default Counter;

需要注意的是,父组件传递给子组件的值是只读的,子组件不能直接修改这些值。如果需要修改这些值,可以通过回调函数的方式将修改后的值传递给父组件,并在父组件中更新状态。例如:

import React, { Component } from 'react';
import Counter from './Counter';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    this.handleCountChange = this.handleCountChange.bind(this);
  }

  handleCountChange(newCount) {
    this.setState({ count: newCount });
  }

  render() {
    return (
      <div>
        <Counter count={this.state.count} onCountChange={this.handleCountChange} />
      </div>
    );
  }
}

export default App;

在子组件 Counter 中,定义一个按钮,点击按钮时调用父组件传递的回调函数 onCountChange,并将修改后的值传递给回调函数:

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.handleButtonClick = this.handleButtonClick.bind(this);
  }

  handleButtonClick() {
    const newCount = this.props.count + 1;
    this.props.onCountChange(newCount);
  }

  render() {
    return (
      <div>
        <p>Count: {this.props.count}</p>
        <button onClick={this.handleButtonClick}>+1</button>
      </div>
    );
  }
}

export default Counter;
React 父子组件 传值

原文地址: https://www.cveoy.top/t/topic/bRmV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录