reactjs - 颜色部分不起作用,代码 React defaultProps 中的错误
问题描述
*嗨,我正在尝试使用 defaultProps 对其进行样式设置。标题部分没问题,我添加正确,但颜色部分不起作用。我应该在哪里改变?
import React from 'react'
// import PropTypes from 'prop-types'
function Button({title,color}) {
return (
<div>
<button style={{color: {color}}}>{title}</button>
</div>
)
}
Button.defaultProps = {
title:'add',
color:"green",
backgroundColor:"orage"
}
// Button.propTypes = {
// color: PropTypes.string.isRequired,
// backgroundColor: PropTypes.string.isRequired,
// title: PropTypes.string.isRequired
// }
export default Button
解决方案
您传递它的方式将不起作用,因为它必须是一个对象。
检查这个。我将样式保存在一个单独的字段中以便更好地理解。
function Button({ title, color }) {
const styles = { color }; // shorthand syntax as property and value are same name
return (
<div>
<button style={styles}>{title}</button>
</div>
);
}
Button.defaultProps = {
title: "add",
color: "green",
backgroundColor: "orage"
};
export default function App() {
return (
<div>
<Button />
</div>
);
}
推荐阅读
- perl - Perl PDL:如何更改矩阵中的值
- c# - 如何在 xamarin 表单中指定触摸的位置(X,Y)?
- python - 使用 keras 将新输入输入到中间层时出现错误
- spring-boot - 春季卡夫卡消费者有时不起作用
- python - 当我在上一个 if 语句中打开子进程时,有没有办法关闭子进程
- javascript - 意外的令牌 { 当我需要“express-fileupload”时
- python - 使用文件夹结构在 Keras 中进行预测时如何获得正确的标签?
- php - 使用键:值对从 JSON 中过滤项目
- jhipster - 我正在将 jhipster 与 MongoDB 一起使用。如何使用 jhipster jdl 为复杂数据结构设计实体(嵌套 JSON)
- matlab - 我们如何将条件语句应用于 julia 中的数组?