Skip to content

Instantly share code, notes, and snippets.

@Yang03
Last active June 6, 2018 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yang03/177f030532600903f142bacca766bc6b to your computer and use it in GitHub Desktop.
Save Yang03/177f030532600903f142bacca766bc6b to your computer and use it in GitHub Desktop.
react
function RadioOption(props) {
return (
<label>
<input type="radio" value={props.value} name={props.name} />
{props.label}
</label>
)
}
function renderChildren(props) {
//遍历所有子组件
return React.Children.map(props.children, child => {
if (child.type === RadioOption)
return React.cloneElement(child, {
//把父组件的props.name赋值给每个子组件
name: props.name
})
else
return child
})
}
//父组件
function RadioGroup(props) {
return (
<div>
{renderChildren(props)}
</div>
)
}
function App() {
return (
<RadioGroup name="hello">
<RadioOption label="选项一" value="1" />
<RadioOption label="选项二" value="2" />
<RadioOption label="选项三" value="3" />
</RadioGroup>
)
}
@Yang03
Copy link
Author

Yang03 commented Jun 6, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment