渲染组件时如何利用点符号? [英] How do I utilize dot notation when rendering components?
问题描述
我有一个简单的组件,应该将不同类型的字段呈现给表单组件:
I have a simple component which is supposed to render different kind of fields into my form component:
import React from "react";
export default class Field extends React.Component {
render() {
switch (this.props.type) {
case 'textarea': {
return (
<div className="col-xs-12">
<textarea
placeholder={this.props.placeholder}
name={this.props.name}
>
</textarea>
</div>
)
}
case 'text': {
return (
<div className="col-md-6 col-lg-4">
<input
type="text"
placeholder={this.props.placeholder}
name={this.props.name}
/>
</div>
)
}
}
}
}
我正在这样的表单组件中使用此组件:
And I'm using this component in my form component like this:
export default class SubmitForm extends React.Component {
render() {
return (
.
.
.
<Field
type="text"
placeholder="something"
name="something"
/>
<Field
type="textarea"
placeholder="another"
name="othername"
/>
.
.
.
)
}
}
我要想到的是按照某种方式实现我的字段组件,以能够使用点表示法,如
What I have in mind is to somehow implement my field component to be able to use dot notation as explained in Using Dot Notation for JSX components which I have seen many other libraries and I want to be able to use this component like this:
<Field.Text name="sth" placeholder="sth" />
<Field.TextArea name="other" placeholder="other stuff" />
但是我无法按照React文档中提到的方式进行操作.我该怎么办?
But I can't do it the way mentioned in React docs. How can I do this?
推荐答案
只需创建单个组件并以以下名称导出它们:
Just create individual components and export them under names:
//Field.js
class TextArea extends React.Component {
...
}
class Text extends React.Component {
...
}
export { Text, TextArea };
然后从模块中导入所有名称:
Then import all the names from the module:
import * as Field from './path/to/Field.js';
或者,如果您希望像这样导出默认对象(这正是文档中的示例所执行的操作,只是以另一种方式):
Or if you prefer exporting a default object like so (which is exactly what the example from the documentation is doing, just in a different way):
export default { Text, TextArea };
将使用对象速记属性并导出默认成员-对象文字.然后,您可以像这样导入它:
Which will use object shorthand properties and export a default member -- an object literal. Then you can import it like so:
import Field from './path/to/Field.js';
最后:
<Field.TextArea ... />
或者,要摆脱点符号(您不能使用默认的导出选项来做到这一点!):
Or, to get rid of dot notation (you can't do this with the default export option!):
import { Text, TextArea } from './path/to/Field.js';
<Text ... />
<TextArea ... />
当然,完全可以通过React文档,使用类表达式进行操作:
Of course, going exactly by the React documentation, you could do, with class expressions:
const Field = {
Text: class Text extends React.Component { //you can omit the class name here
//can be stateless functional component if you don't need state
},
TextArea: class TextArea extends React.Component {
}
}
export default Field;
然后作为默认成员导入并使用点符号.
Then importing as a default member and using dot notation.
这篇关于渲染组件时如何利用点符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!