寻找一种更优雅的方法来使用相似的功能编写多个组件

时间:2019-04-10 18:44:42

标签: javascript reactjs function material-ui higher-order-components

我有一个显示数据的组件,但是还需要保存和处理状态。除了其功能内部的细微差别外,我还有5个其他组件完全相同。我需要帮助找到一种更优雅的方式来编写此代码,而不是拥有6个几乎相同的文件。

我试图为此实例理解和使用HOC,但是每个组件都有自己的提交调用,该调用需要特定于该组件的数据。因此,我似乎找不到找到HOC工作的方法。

这些是我的功能:

  componentDidMount () {
    setTimeout(() => {
      this.setState({ baseForm: this.props.baseData })
      this.getDisable()
      this.setState({ loading: false })
    }, 2000)
  }

  handleSwitch = item => event => {
    this.setState({ [item]: event.target.checked })
  }

  handlePRESubmit () {
    const array = this.state.baseForm
    array.forEach(item => {
      item.isTemplate = false
      item.mark = this.state.mark
      item.isVisible = this.state.visible
      item.genesisId = item._id
    })
  }

  handleSubmit = () => {
    this.handlePRESubmit()
    let formData = this.state.baseForm[0]
    fetch(APIURL, {
      method: 'POST',
      body: JSON.stringify(formData),
    }).then(response => {
      response.json().then(data => {
        let orgId = localStorage.getItem('orgId')
        let sku = { skuId: data.data._id, type: 'verification' }
        fetch(APIURL, {})
          .then(response => response.json())
          .then(data => {})
      })
    })
  }

  toggleDisabled () {
    if (this.state.assigned !== undefined) {
      this.setState({ disabled: !this.state.disabled })
    }
  }

  getDisable () {
    setTimeout(() => {
      const result = this.props.assignedSku.find(e => e.name === 'Base')
      this.setState({ assigned: result })
      if (this.state.assigned !== undefined) {
        this.setState({ mark: true })
        this.setState({ visible: true })
      }
    }, 1000)
  }

  handleMenu = event => {
    this.setState({ anchorEl: event.currentTarget })
  }

  handleClose = () => {
    this.setState({ anchorEl: null })
  }

这是我的卡

        <Card id='partner-sku-card'>
          <CardHeader
            title={base.name}
            subheader={'$' + ' ' + base.price}
            action={
              <div>
                <IconButton onClick={this.handleMenu}/>
              </div>
            }
          />
          <Menu
            anchorEl={anchorEl}
            open={Boolean(anchorEl)}
            onClose={this.handleClose}
          >
            <MenuItem disabled={this.state.disabled ? 'disabled' : ''}>
              Edit
            </MenuItem>
          </Menu>
          <CardActions>
            <FormControlLabel
              control={
                <Switch
                  checked={this.state.mark}
                  onChange={this.handleSwitch('mark')}
                  value='mark'
                />
              }
            />
            <FormControlLabel
              control={
                <Switch
                  checked={this.state.visible}
                  onChange={this.handleSwitch('visible')}
                  value='visible'
                />
              }
            />
            <Button onClick={this.handleSubmit}>
              Submit
            </Button>
          </CardActions>
        </Card>

同样,所有这些代码再次被写入其他5个文件中。我需要一种优雅的方法来替换“ Base” /“ base”一词。可以说我有基本,中,上。我需要所有这些功能才能同时使用这3个功能,但最后仍要生产同一张卡。 感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

创建一个名为CardWrapper的组件。然后在每个其他文件中像这样调用CardWrapper

class First extends Component {
    handleSwitch = () => {
        //its own implementation
    }

    handlePreSubmit = () => {
        //its own implementation
    }

    handleSubmit = () => {
        //its own implementation
    }
    //other methods that you need for each component to be different

    render(){
        return (
            <CardWrapper handlePreSubmit={this.handlePreSubmit} handleSubmit={this.handleSubmit} handleSwitch={this.handleSwitch} />
        )
    }
}

请记住,您应该将所有这些添加到共享CardWrapper组件的所有文件中。

然后在CardWrapper中通过this.props进行访问。例如最后,当您拥有Submit Button时,其变化将如下所示:

<Button onClick={this.props.handleSubmit}>
    Submit
</Button>