【发布时间】:2016-05-18 06:00:11
【问题描述】:
我想要实现的目标:从嵌套元素中获取数据。
我是如何尝试实现它的: 使用子元素的ref 属性在父元素中获取该元素。不起作用,因为 this.refs 似乎只在顶部组件中包含 refs,而不是嵌套组件。
SubmitStoryForm.jsx 有嵌套组件TextInput.jsx,这是一个简单的<input /> 组件。
所以我的表单中有两个元素,SubmitStoryForm.jsx:
<TextInput label="Story name" refer="titleInput" />
<textarea className="materialize-textarea" ref="bodyInput" />
refer 属性是放在TextInput 中的ref 属性中的:
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 属性是在父元素中定义的。但是当我把这个责任转嫁给孩子时,TextInput、ref 不可用。
这是我应该如何构建我的代码的方式吗?
当我尝试做时代码失败:
this.refs.titleInput.value
在SubmitStoryForm.jsx,但是
this.refs.bodyInput.value
工作正常。
错误:
Uncaught TypeError: Cannot read property 'value' of null
【问题讨论】:
标签: javascript meteor reactjs