嗨,我是 ReactJs 的新手。我发现文档很难消化,因此我在一些非常基本的事情上遇到了麻烦。我正在尝试在我的表单中使用此文本输入组件,但我不知道如何动态设置值。
这是文本输入组件
import React, { PropTypes } from 'react';
import FormField from './FormField';
var TextInput = React.createClass({
propTypes: {
field: PropTypes.object.isRequired
},
render() {
var {field, help, label, ...inputProps} = this.props
return <FormField field={field} help={help} inputProps={inputProps} label={label}>
<input
{...inputProps}
className="form-control"
name={field.name}
value={field.value}
onBlur={field.onBlur}
onChange={field.onChange}
/>
</FormField>
}
})
export default TextInput
这是我使用它的地方
import React from 'react';
import ProfileSideBar from './ProfileSideBar';
import ProfileSectionLabel from './ProfileSectionLabel';
import TextInput from '../forms/TextInput';
class ProfileHome extends React.Component {
render() {
return <div id='profile-wrapper'>
<tr width='100%'>
<td width="33%"> Location </td>
<td width="33%">
<TextInput field={location}
style={{height: 40,
borderColor: 'orange',
borderWidth: 1}}>
</TextInput>
</td>
</tr>
</div>
在我使用TextInput的地方,我正在尝试设置默认值。所以像这样:
位置{ 值:"NY"}因此,如果它存在,它将填充 ny,如果不存在,它将是空白的。
我试过了
<TextInput value={value}>
它只是不运行。当我删除值=值时,页面呈现,但没有我需要的数据。
我知道我必须(或者至少我认为我知道)设置状态或其他东西并将其绑定到我的配置文件主页组件...我只是不知道怎么做。 如果有人能告诉我如何做到这一点,我会很高兴。 如果可能的话,请给我一个很好的资源。 我觉得棱角更容易上手。
你试过用defaultValue
吗?
<TextInput defaultValue={value}>
这将呈现作为 defaultValue 传递的任何内容,但是您仍然需要绑定value
和onChange
以反映用户交互,因为您将<input>
用作受控组件。有关更多信息,请参阅 React 的受控组件。
这里有一种方法可以解决这个问题。
首先,创建 TextInput 类并在构造函数中设置文本值的初始状态,并将正确的"this"上下文绑定到接下来要创建的方法:
class TextInput extends Component {
constructor(props) {
super(props);
this.state = { text: 'ny' };
this.onInputChange = this.onInputChange.bind(this);
}
然后,创建 TextInput 类的方法,该方法处理对输入值的更改并相应地设置状态:
onInputChange(event) {
this.setState({ text: event.target.value });
}
最后,在渲染函数中,你的输入字段看起来像这样(加上你想给它的任何其他道具):
<input
value={ this.state.text }
onChange={ this.onInputChange }
/>
至于资源,React 文档非常棒,我发现 Stephen Grider 关于 udemy 的课程是关于 React: https://www.udemy.com/react-redux/learn/#/的最佳教程。 在进入本教程的 Redux 部分之前,请务必了解 React 的基础知识(状态和 props) - 事情变得非常有趣,但肯定更复杂。