繁体   English   中英

如何在子组件内部调用父组件的功能?

[英]How can I call the function of a parent component inside of a child component?

首先,我比较新,所以请随时批评我遇到的任何类型的架构问题,我觉得有更好的方法来写这个,但我一直在努力让它工作一个小时。

父元素(TileGrid):

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

export default class TileGrid extends Component {
    constructor(props) {
        super(props);
    }

    updateTileData(value) {
        {/* Do something with value here */}
    }

    render() {
        this.test()
        return (
            {/* The Tile component is a custom button with some richer features. */}
            <Tile name='Dog' image='dog' /> 
        )
    }
}

子元素(平铺):

import React from 'react';
import ButtonBase from '@mui/material/ButtonBase';
import './styles/Tile.css';

function Tile(props) {
    return(
        <div className="Tile">
            <ButtonBase onClick={/* This is where the Tile needs to call updateTileData in TileGrid */}>
            Button
            </ButtonBase>
        </div>
    );
}

export default Tile;

所以在 TileGrid 中有一个名为 updateTileData 的函数,它将获取一些数据并使用它来更新 TileGrid 的状态。 Tile 组件作为 TileGrid 组件中的一个子组件存在。 我在这里尝试了各种各样的东西,但这似乎是一个简单的任务,有没有更好的方法来编写这个功能? 我不受代码中的任何限制,请告诉我是否有更好的方法来做到这一点。 我还在学习这个框架,这个问题让我挂了。 谢谢,阿切尔。

将函数从父级传递给子级作为道具示例:

<Child func={this.functionInParent} />

props.func() //called inside child

您需要将道具传递给子元素并调用它。

  import React, { Component } from 'react'
    import Tile from './Tile.js';
    
    export default class TileGrid extends Component {
      
 
    updateTileData(value) {
        {/* Do something with value here */}
    }

   

    render() {
        this.test()
        return (
            {/* The Tile component is a custom button with some richer features. */}
            <Tile name='Dog' image='dog' setValue={this.updateTileData} /> 
        )
    }
}

子元素:

import React from 'react';
import ButtonBase from '@mui/material/ButtonBase';
import './styles/Tile.css';

function Tile(props) {
    return(
        <div className="Tile">
            <ButtonBase onClick={()=>props.setValue("your value")}>
            Button
            </ButtonBase>
        </div>
    );
}

export default Tile;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM