我的代码的目标是使 InputGroup.js
中的 properties
可用于最低级别组件中的 this.props
TextInput.js、Checkbox.js
等等。
为此,我创建了一个名为 InputComponent.js
的非常简单的组件,我在这里所做的是创建 this.prpt
并分配 this。 props
到它,以便可以在 TextInput.js
中使用它代替 this.props
。
我似乎很冗长,我认为有更好的方法,但我想知道是否有更好的方法来做到这一点。
简而言之,我想使用 this.props
,在 TextInput.js
上使用,而不是 this.props.properties
或 this.props.data
.
InputGroup.js
InputGroup.js
适用于与传入的 input_type 值对应的组件。
import React, { Component } from 'react';
import {INPUT_TYPES as T} from './constants';
import {TextInput, CheckboxInput, SelectInput, MobileInput, DateInput, SnsAuthInput} from '.';
class InputGroup extends Component {
constructor(props){
super(props);
}
render() {
let input_type = this.props.type;
let switcher = {
[T.TEXT]: TextInput,
[T.CHECKBOX]: CheckboxInput,
[T.SELECT]: SelectInput,
[T.MOBILE]: MobileInput,
[T.DATE]: DateInput,
[T.SNSAUTH]: SnsAuthInput
}
let TagName = (input_type < Object.keys(switcher).length) ? switcher[(input_type)] : undefined;
if (TagName) {
return <TagName properties={this.props} />
}
return <div></div>
}
}
InputComponent.js
import React, { Component } from 'react';
class InputComponent extends Component {
constructor(props){
super(props);
this.prpt = this.props.properties;
}
}
export default InputComponent ;
TextInput.js
import React, { Component } from 'react';
import InputComponent from './InputComponent';
class TextInput extends InputComponent {
constructor(props) {
super(props);
}
render() {
let {input_id, text, isRequired, error} = this.prpt;
return (
<div className="input-group input-text">
<label htmlFor={input_id} className="blind">{text}</label>
<input type="text" id={input_id} placeholder={text} required={isRequired}/>
<span className="id-error">{error}</span>
</div>
);
}
}
export default TextInput ;
<小时/>
[编辑] 我认为我的问题标题没有描述这一点,所以我更正了它。
<小时/>[编辑] 现在我明白了这一点,所以我更正了标题并添加了众所周知的解决方案。
```
InputGroup.js - 编辑
class InputGroup extends Component {
constructor(props){
super(props);
}
render() {
let input_type = this.props.type;
let switcher = {
[T.TEXT]: TextInput,
[T.CHECKBOX]: CheckboxInput,
[T.SELECT]: SelectInput,
[T.MOBILE]: MobileInput,
[T.DATE]: DateInput,
[T.SNSAUTH]: SnsAuthInput
}
let TagName = (input_type < Object.keys(switcher).length) ? switcher[(input_type)] : undefined;
if (TagName) {
return <TagName {...this.props} />
}
return <div></div>
}
}
最佳答案
我认为您正在寻找类似的东西。
<Parent propX={x} propY={y} />
<Child {...props} />
关于javascript - 使用调用者组件的相同属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46154229/