You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React:子组件触发onClick事件时如何调用父组件的事件函数

实现方案

在React中要实现子组件触发父组件内定义的方法,直接通过props将父组件方法传递给子组件,子组件在对应触发时机调用传入的props方法即可,具体修改如下:

  • 第一步:修改父组件,给子组件传递changeBackground方法,同时修正原代码中setState语法错误、primaryDark属性拼写错误:
// 父组件修改后代码
class App extends React.Component {
  constructor(props) {
    super(props)
    this.state ={
      primary: '',
      // 修正拼写错误:原来的prmaryDark少了字母i
      primaryDark: ''
    }
  }

  changeBackground = () => {
    let randomNum = Math.floor(Math.random()*backgroundColors.length)
    // 修正setState用法:setState是方法,不是直接赋值
    this.setState({
      primary: backgroundColors[randomNum].main,
      primaryDark: backgroundColors[randomNum].dark
    })
  }
  

  render() { 
    return (
      <div className="App">
        {/* 给子组件传自定义props,值为父组件的changeBackground方法 */}
        <QuoteBox onChangeBg={this.changeBackground} />
      </div>
    );
  }
}
  • 第二步:修改子组件,接收父组件传入的方法,在按钮点击时同时执行原有拉取名言逻辑和背景切换逻辑:
// 子组件修改后代码
export default function QuoteBox({ onChangeBg }) {
  const [newQuote, setNewQuote] = useState('');
  const [author, setAuthor] = useState('');

  const fetchRandomQuote = () => {
    fetch(url)
    // some method
  }

  return (
    <div className="QuoteBox" >
        <Text quoteText={newQuote} author={author}  />
        <Banner>
            <Links />
            {/* 点击按钮时同时执行两个方法 */}
            <NewQuoteButton 
              onClick={() => {
                fetchRandomQuote()
                onChangeBg()
              }} 
              className="NewQuoteButton Button" 
            />
        </Banner>
    </div>
  );
}

如果你不需要点击按钮时同时执行拉取名言的逻辑,直接把onClick的值替换为onChangeBg即可。

内容的提问来源于stack exchange,提问作者Anna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 16:24:06