How do I utilize dot notation when rendering components?

一笑奈何 提交于 2019-12-04 07:48:09

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';

And finally:

<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 ... />

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.

Simply following the docs.

const Field = {
  Text: function Text(props) {
    return <div className="col-md-6 col-lg-4">
            <input
              type="text"
              placeholder={this.props.placeholder}
              name={this.props.name}
            />
          </div>;
  },
  Textarea: function Textarea(props) {
    return <div className="col-xs-12">
            <textarea
              placeholder={this.props.placeholder}
              name={this.props.name}
            >
            </textarea>
          </div>;
  }
}

Then when your dot usage

<Field.Text placeholder="something" name="something" />
suyesh
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>
        )
      }
    }
  }
}

chnage this as following way

const Field = {
    text: function(){
      // your text code
    }
}

export default Field;

Same way they have mentioned in the facebook react docs. Instead of component you can return object which contain your functions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!