React 中 refs 干嘛用的?
Refs
提供了一种访问在render
方法中创建的 DOM 节点或者 React 元素的方法。在典型的数据流中,props
是父子组件交互的唯一方式,想要修改子组件,需要使用新的pros
重新渲染它。凡事有例外,某些情况下咱们需要在典型数据流外,强制修改子代,这个时候可以使用 Refs
。
咱们可以在组件添加一个 ref
属性来使用,该属性的值是一个回调函数,接收作为其第一个参数的底层 DOM 元素或组件的挂载实例。
class UnControlledForm extends Component {
handleSubmit = () => {
console.log("Input Value: ", this.input.value);
};
render() {
return (
<form onSubmit={
this.handleSubmit}>
<input type="text" ref={
(input) => (this.input = input)} />
<button type="submit">Submit</button>
</form>
);
}
}
请注意,input
元素有一个ref
属性,它的值是一个函数。该函数接收输入的实际 DOM 元素,然后将其放在实例上,这样就可以在 handleSubmit
函数内部访问它。
经常被误解的只有在类组件中才能使用 refs
,但是refs
也可以通过利用 JS 中的闭包与函数组件一起使用。
function CustomForm({
handleSubmit }) {
let inputElement;
return (
<form onSubmit={
() => handleSubmit(inputElement.value)}>
<input type="text" ref={
(input) => (inputElement = input)} />
<button type="submit">Submit</button>
</form>
);
}
对于store的理解
Store 就是把它们联系到一起的对象。Store 有以下职责:
- 维持应用的 state;
- 提供 getState() 方法获取 state;
- 提供 dispatch(action) 方法更新 state;
- 通过 subscribe(listener)注册监听器;
- 通过 subscribe(listener)返回的函数注销监听器
React中props.children和React.Children的区别
在React中,当涉及组件嵌套,在父组件中使用props.children
把所有子组件显示出来。如下:
function ParentComponent(props){
return (
<div>
{
props.children} </div>
)
}
复制代码
如果想把父组件中的属性传给所有的子组件,需要使用React.Children
方法。
比如,把几个Radio组合起来,合成一个RadioGroup,这就要求所有的Radio具有同样的name属性值。可以这样:把Radio看做子组件,RadioGroup看做父组件,name的属性值在RadioGroup这个父组件中设置。
首先是子组件:
//子组件
function RadioOption(props) {
return (
<label>
<input type="radio" value={
props.value} name={
props.name} />
{
props.label} </label>
)
}
复制代码
然后是父组件,不仅需要把它所有的子组件显示出来,还需要为每个子组件赋上name属性和值:
//父组件用,props是指父组件的props
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)} <