这假设
MyComponent
在接受一个或多个反应时会保持一致
Input
S.
工作示例
以下内容:
https://codesandbox.io/s/045kw2pq30
组件/非输入.js
import React, { Fragment } from "react";
import PropTypes from "prop-types";
const NonInput = props => (
<code>
<pre>{JSON.stringify(props, null, 4)}</pre>
</code>
);
NonInput.propTypes = {
props: PropTypes.objectOf(PropTypes.string)
};
export default NonInput;
组件/输入.js
import React, { Fragment } from "react";
import PropTypes from "prop-types";
const Input = ({ newProp, ...props }) => (
<Fragment>
{console.log(newProp)}
<input className="uk-input" {...props} />
</Fragment>
);
Input.propTypes = {
newProp: PropTypes.string,
props: PropTypes.objectOf(PropTypes.string)
};
export default Input;
组件/mycomponent.js
import React, { PureComponent, cloneElement } from "react";
import PropTypes from "prop-types";
import Input from "./Input";
const shapeOfChildren = PropTypes.shape({
type: PropTypes.oneOf([Input]).isRequired,
props: PropTypes.shape({
name: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
placeholder: PropTypes.string.isRequired
}).isRequired
});
class MyComponent extends PureComponent {
renderChildren = child => (
<div className="inner">{cloneElement(child, { newProp: "blaaa" })}</div>
);
render = () => (
<div className="uk-form-large">
{React.Children.map(this.props.children, this.renderChildren)}
</div>
);
}
MyComponent.propTypes = {
children: PropTypes.oneOfType([
shapeOfChildren,
PropTypes.arrayOf(shapeOfChildren)
]).isRequired
};
export default MyComponent;
组件/示例.js
(删除)
NonInput
,保存,然后刷新页面以删除PropType警告--如果希望它显示更明确的警告,请编写一个
custom validator function (example toward the bottom)
)
import React from "react";
import MyComponent from "./MyComponent";
import Input from "./Input";
import NonInput from "./NonInput";
export default () => (
<MyComponent>
<Input name="firstName" type="text" placeholder="First Name" />
<Input name="lastName" type="text" placeholder="Last Name" />
<NonInput name="lastName" type="text" placeholder="Last Name" />
</MyComponent>
);