我想要实现的目标:从嵌套元素获取数据。
我如何尝试实现它:使用ref
子元素的属性以获取父元素中的该元素。不起作用,因为 this.refs
似乎只包含 refs
在顶部组件中,而不是嵌套组件中。
SubmitStoryForm.jsx
具有嵌套组件 TextInput.jsx
,这是一个简单的<input />
组件。
所以我的表单中有两个元素, SubmitStoryForm.jsx
:
<TextInput label="Story name" refer="titleInput" />
<textarea className="materialize-textarea" ref="bodyInput" />
refer
属性是放入 ref
中的内容TextInput
中的属性:
import React, {Component, PropTypes,} from 'react';
export default class TextInput extends Component {
render() {
const refer = this.props.refer;
console.log(refer);
const id = 'id_'+refer;
const type = this.props.type;
const col = this.props.col;
const label = this.props.label;
return (
<div className=
{col ? 'input-field col ' + col : 'input-field col s3'}>
<input
placeholder={this.props.placeholder}
id={id}
ref={refer}
type={type ? type : 'text'} />
{label ?
<label for={id}>
{this.props.label}
</label> : ''}
</div>
)
}
}
TextInput.propTypes = {
refer: PropTypes.string.isRequired,
};
适用于 textarea
元素因为 ref
属性在父级中定义。但当我把这个责任交给一个 child 时,TextInput
, ref
不可用。
这是我应该如何构建我的代码吗?
当我尝试执行以下操作时,代码失败:
this.refs.titleInput.value
在 SubmitStoryForm.jsx
,但是
this.refs.bodyInput.value
工作正常。
错误:
Uncaught TypeError: Cannot read property 'value' of null
最佳答案
虽然您可以使用refs
要让父组件访问子组件的数据,您确实不应该这样做。 (Netflix 是 React 的重度用户,甚至有一条规则“永远不要引用”参见 this video ,距离大约 10m)。
在 99.9% 的情况下,您可以使用任何东西 refs
对于,可以通过其他方式更好地解决。
在您的示例中,父级不应需要通过 refs 访问子级的数据:
- 如果数据与子 props 有关,则父级已经知道该数据,因此:不需要引用。
- 如果数据是关于子状态的,那么使用 refs 来访问该数据确实是在欺骗 React:状态不应该可以从组件外部直接访问。
- 如果数据不在子 props 中,也不在子 state 中,那么这可能是一个需要修复的设计遗漏,因为与应用相关的数据应该是 props 或 state。
就您而言,更好的 ref
-less 解决方案是:
- 通过为
textInputValue
添加状态,使您的父组件有状态和textAreaValue
- 添加
onChange()
父级中文本区域的处理程序(因为该组件是由父级直接渲染的),它更新状态 - 通过
this.state.textInputValue
和一个changeHandler={this.textInputChangeHandler}
作为你的<TextInput>
的 Prop 组件 - 在您的
<TextInput>
中组件,添加onChange={this.props.changeHandler}
到输入组件,该组件调用父组件上的方法来更新状态 - 在父级的更改处理程序中,您可以阅读
event.target.value
获取字段的新值。
通过这样做,您可以将输入值放入父级中的状态,并将其中一个值作为 props 传递给子级。
奖励:在提交表单的任何代码中,您不需要再次读取所有字段。您可以简单地从 this.state
获取所有信息发送到任何地方。
关于javascript - meteor - 从 child 到 parent 获得值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37286356/