首页 > 解决方案 > 颜色部分不起作用,代码 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

标签: reactjsbuttoncolorstitle

解决方案


您传递它的方式将不起作用,因为它必须是一个对象。

检查这个。我将样式保存在一个单独的字段中以便更好地理解。

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>
  );
}


推荐阅读