ReactJS: Как визуализировать разметку с помощью .map() и ReactCreateElement

#javascript #reactjs #jsx

Вопрос:

render Метод моего компонента react в настоящее время выглядит следующим образом (рендеринг нескольких кнопок и другой разметки с использованием React.createElement ):

 class Mychart extends React.Component {

constructor(props) {
  
  super(props);
  this.state = {
    dataset: [...],
    title: 'Title here'
  };
  this.updateChart = this.updateChart.bind(this);
  this.myRef = React.createRef(); 
  
}

updateChart(network) {
....
}

render() {

  const title = (style, children) => React.createElement('h4', { style }, children);
  const button = (props, children) => React.createElement('button', props, children);
  const div = (props, children) => React.createElement('div', props, children);
  const titleStyle = {backgroundColor: '#000', color: '#fff'}

  return (
    [
      title(titleStyle, this.state.title),
      button({onClick: () => {this.setState({title: 'Sharestream of All Networks'}, () => this.updateChart('all'))}}, 'Show All'),
      button({onClick: () => {this.setState({title: 'Sharestream of CBS'}, () => this.updateChart(['CBS']))}}, 'Show CBS only'),
      div({ref: this.myRef})
    ]
  );
}
 

Тем не менее, я хотел бы иметь возможность динамически генерировать эти кнопки. Я не знаю, как это сделать. Это то, что я пробовал.

Я могу добавить этот метод в свой компонент react, который возвращает массив кнопок, созданных с помощью React.createElement:

 createButtons(buttonArr) {
  
  const button = (props, children) => React.createElement('button', props, children);
  
  return buttonArr.map((button) => {
    return button({onClick: () => {this.setState({title: button.title}, () => this.updateChart(button.update))}}, button.label)
  })

}
 

Я бы назвал createButtons метод так (однако я не уверен, где и как я бы добавил эту часть):

   const myButtons = [
    {title: 'Sharestream of All Networks', update: 'all', label: 'Show All'}, 
    {title: 'Sharestream of CBS', update: ['CBS'], label: 'Show CBS only'}
  ];
  {this.createButtons(myButtons)}