ReactJS 动态调用自定义 class
ReactJS dynamically call custom class
我正在尝试设置一种从某些 json 值动态创建表单对象的方法。本质上,我的 json 表单对象类型和属性。我将该类型传递给 FormInput class,然后调用包含实际表单对象的自定义 class。我现在的问题是,当我传入自定义 class 名称 "TextInput" (this.props.formElementType) 时,React 只是创建一个名为 'textinput' 的元素,而不是调用 class .它似乎不喜欢传递字符串,而只需要 class 名称。本质上,...
TextInput = React.createClass({...})
...
FormItem = React.createElement(<TextInputPassedAsAString>, {...})
我不确定是否可以通过传递字符串以这种方式调用自定义 class。由于我是 React 的新手,因此我需要有关此实现的帮助或更好的想法。
下面是所有相关代码,从子项开始到最终渲染块结束。请原谅伪coffeescript。
文本输入
TextInput = React.createClass
handleChange: (event)->
this.setState
value: event.target.value
render: ->
React.createElement('label', {
value: this.props.formElementLabel
})
React.createElement('input', {
id: this.props.formElementID,
type: 'text'
})
module.exports = TextInput
表单元素
FormElement = React.createClass
render: ->
R.div(null,
React.createElement(this.props.formElementType, {
formElementID: this.props.formElementID,
formElementLabel: this.props.formElementLabel
})
module.exports = FormElement
初始call/final渲染
React.createElement(FormElement, {
formElementType: 'TextInput',
formElementID: 'firstFormElement',
formElementLabel: 'First text input'
})
嗯,最好的、最容易推理的方法可能是在进行最终渲染的模块中要求 TextInput
。在那里创建它,将其他道具传递给它,然后将这个创建的组件传递给 FormElement
而不是传递组件的字符串表示。
一种更动态地执行此操作的方法是拥有一个模块,该模块将每个动态组件导出为导出时的 property/method。类似于:
module.exports = {
TextInput: ...
}
然后当你渲染的时候你可以传入这样的东西:
myImports[json.formElementType]
我正在尝试设置一种从某些 json 值动态创建表单对象的方法。本质上,我的 json 表单对象类型和属性。我将该类型传递给 FormInput class,然后调用包含实际表单对象的自定义 class。我现在的问题是,当我传入自定义 class 名称 "TextInput" (this.props.formElementType) 时,React 只是创建一个名为 'textinput' 的元素,而不是调用 class .它似乎不喜欢传递字符串,而只需要 class 名称。本质上,...
TextInput = React.createClass({...})
...
FormItem = React.createElement(<TextInputPassedAsAString>, {...})
我不确定是否可以通过传递字符串以这种方式调用自定义 class。由于我是 React 的新手,因此我需要有关此实现的帮助或更好的想法。
下面是所有相关代码,从子项开始到最终渲染块结束。请原谅伪coffeescript。
文本输入
TextInput = React.createClass
handleChange: (event)->
this.setState
value: event.target.value
render: ->
React.createElement('label', {
value: this.props.formElementLabel
})
React.createElement('input', {
id: this.props.formElementID,
type: 'text'
})
module.exports = TextInput
表单元素
FormElement = React.createClass
render: ->
R.div(null,
React.createElement(this.props.formElementType, {
formElementID: this.props.formElementID,
formElementLabel: this.props.formElementLabel
})
module.exports = FormElement
初始call/final渲染
React.createElement(FormElement, {
formElementType: 'TextInput',
formElementID: 'firstFormElement',
formElementLabel: 'First text input'
})
嗯,最好的、最容易推理的方法可能是在进行最终渲染的模块中要求 TextInput
。在那里创建它,将其他道具传递给它,然后将这个创建的组件传递给 FormElement
而不是传递组件的字符串表示。
一种更动态地执行此操作的方法是拥有一个模块,该模块将每个动态组件导出为导出时的 property/method。类似于:
module.exports = {
TextInput: ...
}
然后当你渲染的时候你可以传入这样的东西:
myImports[json.formElementType]