javascript - 为 React Component 提供替代渲染方法

标签 javascript reactjs components

在我的应用程序中,我有几个表单字段组件,它们的行为方式都相同,但看起来略有不同。我希望能够使用单个表单域组件的状态和类方法,同时提供某种替代渲染方法,以便我可以即时自定义此元素的外观。我知道我可以包装 child ,然后在组件中使用 props.children。但我希望以某种方式重新使用组件方法:

class Parent extends React.Component {
  render() {
    <div className="parent">
      <ChildFormField
        renderAlternate={self => {
          return (
            <div className="child--alternate">
              <input onChange={self.doThing} />
            </div>
          );
        }}
      />
    </div>
  }
}

// And the child component look something like...
class ChildFormField extends React.Component {
  state = {
    value: null
  }

  doThing = value => {
    return this.setState({ value });
  }

  render() {
    if (this.props.renderAlternate !== undefined) {
      return this.props.renderAlternate();
    }

    // standard return
    return <div />;
  }
}

除了基本用法之外,我对 React 还比较陌生。是否有推荐的方法来实现此功能?

最佳答案

您的renderAlternate 函数需要一个参数self。所以调用的时候需要传递this

return this.props.renderAlternate(this);

参见 https://codesandbox.io/s/w759j6pl6k作为您的代码示例。

关于javascript - 为 React Component 提供替代渲染方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53709856/

相关文章:

javascript - 将数据发送到 EmberJS 中的嵌套 Controller / View

javascript - 重新加载页面我丢失了表单中的所有值

spring-boot - Spring Boot 如何自动包含 pom 文件中包含的依赖项中的代码?

delphi - 使用 DBComboBox 相对于 ComboBox 的优势?

javascript - onClick 事件的调度操作

Reactjs - 将状态值从一个组件传递到另一个组件

javascript - 向从特定数字开始的每个 x 列表添加边框

javascript - 弹出警报

javascript - React 路由组件类型错误 : history is undefined

javascript - 使用 webdriverio 从 React 包裹的 span 获取文本