Last active
June 6, 2018 09:35
-
-
Save Yang03/177f030532600903f142bacca766bc6b to your computer and use it in GitHub Desktop.
react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment