gpt4 book ai didi

reactjs - 在组件之间传递 Props

转载 作者:行者123 更新时间:2023-12-03 14:21:22 25 4
gpt4 key购买 nike

我正在创建一个 Playground 来学习 react ,但我在组件之间传递 Prop 时遇到了障碍。我基本上有两个组件,一个是基本组件,另一个将其渲染在页面上并带有一些附加组件(为了简单起见,我已将其删除)。我本质上希望能够在其他地方重复使用这些项目。

我希望能够在渲染示例中的组件时指定它是否为 type=submit(如果未指定任何内容),则默认为 type=button

我显然错过了这里的重点,因为我使用下面的代码收到错误Cannot read property 'props' of undefined。任何帮助将不胜感激

按钮组件

import React, {PropTypes} from 'react';
import './button_component.scss';

const propTypes = {
type: PropTypes.string
}

const ButtonComponent = () => {
return <button type={this.props.type}>button</button>
}

ButtonComponent.propTypes = propTypes;
export default ButtonComponent;

然后我有一个输出我的项目的组件

import React from 'react';
import ButtonComponent from './button_component';
import Example from './example'

export default () =>
<Example>
<ButtonComponent type='button' />
</Example>;

最佳答案

ButtonComponentfunctional component 。因此,您不能使用 this.props在其代码中。

你应该介绍props论据

const ButtonComponent = (props) => {
return <button type={props.type}>button</button>
}

对象解构和defaultProps可以帮助您使代码更简单

const ButtonComponent = ({ type }) => {
return <button type={type}>button</button>
}

ButtonComponent.defaultProps = {
type: 'button'
}

那么你可以简单地输入 <ButtonComponent />呈现一个按钮。

关于reactjs - 在组件之间传递 Props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38450147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com