javascript - 在 React.js 中有条件地渲染不同元素时传递相同的 props

标签 javascript reactjs chart.js

我有一个名为 Chart 的 React 组件。我想根据从父级传递的 Prop 在其中渲染不同的图表,但具有完全相同的配置。最好的方法是什么?

class Chart extends Component {

  static propTypes = {
    type: PropTypes.string.isRequired
  }

  state = {
    chartData: {
      // some data here 
    }
  }

  render(){
    return(
      this.props.type === 'line' ?
      { <Line
        data={this.state.chartData}
        options={{
          title: {
            display: true,
            text: 'Cities I\'ve lived in',
            fontSize: 25
          },
          legend: {
            display: true,
            position: 'right',
            labels: {
              fontColor: '#000'
            }
          }
        }}
      /> } : this.props.type === 'bar' ?
      { <Bar
          //same stuff here as <Line />
        />
      } : this.props.type === 'pie' ?
      { <Pie
          //same stuff here as <Line />
        /> }
      }
    );
  }
}

不认为这很重要,因为这个问题是通用的,但我正在使用 react-chartjs-2/chart.js 2 库来渲染图表。

注意:我尝试使用变量名称代替 Line/Bar/Pie,但如果我使用 JSX 或呈现非 html 标记,则它不起作用。也欢迎使用 JSX 和非 html 标签来解决这个问题的更好方法。

最佳答案

有两件事:

  • 使用无状态组件,在您的示例中您没有使用状态。
  • 使用 switch 代替 if 语句。

您的新组件 ...chart 是解构的 props。阅读有关解构的更多信息 MDN .

// Chart.js - new component

export const Chart = ({ type, ...chart }) => { 
  switch(type) {
    case 'line':
      return <Line {...chart} />
    case 'bar':
      return <Bar {...chart} />
    case 'pie':
      return <Pie {...chart} />
    default:
     return null;
  }
}

使用示例

// App.js 

render() {
  return (
    <div>
      <Chart type="line" options={optionsObject} whateverProp="whatever" />
      <Chart type="bar" options={optionsObject} whateverProp="whatever" />
      <Chart type="pie" options={optionsObject} whateverProp="whatever" />
    </div>
  )
}

关于javascript - 在 React.js 中有条件地渲染不同元素时传递相同的 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480194/

相关文章:

javascript - 切换 jQuery 1.3.2 → 1.4.4 时出错

reactjs - 如何在react-apollo中模拟GraphQL API以进行离线API调用

javascript - ReferenceError:初始化前无法访问 'search'

javascript - 如何使用 Charts.JS 创建显示相对值而不是绝对值的堆积条形图?

javascript - 在 MongoDB 中最后对 Null 值进行排序

javascript - 如何在没有 npm 的情况下使用 Vue.js 元素?

php - 在 html 中添加多行时表单的输出给我 Word "ARRAY"

reactjs - React + Firebase存储+文件上传和进度显示

javascript - 如何使用 chartjs 2 从图表外部触发悬停模式?

javascript - 图表js将米平方/上标放在y轴上