【发布时间】:2017-03-05 16:03:40
【问题描述】:
我正在学习 ReactJS。我编写了一个 Web 应用程序,它应该显示一个输入文本和一个“确认”按钮,当按下它时,它会显示一个带有“返回”按钮的第二个输入文本,该按钮会删除新的输入。当显示第二个时,第一个输入和第一个按钮被禁用。
但是,我当前的脚本不被接受。我在将函数作为道具传递给函数 FormRender 以及在 FormRender 对象本身中指示属性“已禁用”(它声称已找到“意外令牌”)时遇到问题。
有没有更好的方法?
function FormRender (props) {
return (
<div>
<input type = "text" placeholder = {this.props.holder} {this.props.disable} />
<button onClick = {this.props.Click()} {this.props.disable} > {this.state.value} </button>
</div>
);
};
var R = React.createClass ({
getInitialState: function () {
return { names: [], disable: false }
},
update: function () {
return this.state.disable ? "disabled" : "";
},
componentDidMount: function () {
var a = this.state.names;
a.push ( <FormRender holder = 'Name' value = 'Confirm' Click = {this.In}, disable: {this.update} /> );
this.setState ( { names: a } );
this.forceUpdate();
},
In: function () {
var a = this.state.names;
this.setState ( { disable: true } );
a.push ( <FormRender holder = 'Surname ' value = 'Back' Click = {this.Out} disable: "" /> );
this.setState ( { names: a } );
this.forceUpdate();
},
Out: function () {
var a = this.state.names;
this.setState ( { disable: false } );
a.splice(a.length-1,1);
this.setState ( { names: a } );
this.forceUpdate();
},
render: function () {
return (
<div>
{this.state.names}
</div>
);
}
});
【问题讨论】:
-
可以使用
disabled={true/false},不需要进行字符串转换。 Example. -
@Roc 您的代码中几乎没有错误。 1. 功能组件没有状态所以:
{this.state.value}将不起作用 2. 在 FormRender 中,您可以通过第一个参数访问道具,因此不要使用this.props.disable而是使用 'props.disable' 3. 当您分配事件时像onClick这样的处理程序,您应该分配函数:onClick={this.props.Click}(不带括号) 4. 定义道具时,您不能使用':'作为分配运算符。在大多数地方你使用'=',但在少数地方你使用':'。你必须改变它。也许你应该使用Click = {this.In.bind(this)} -
我忘记了您的“意外令牌”错误。在 FormRender 中使用
disbale={this.props.disable}。 -
@Grajek 完成了,但无论我用什么符号表示道具,我都不允许使用它
-
@Roc 你能更新代码吗?
标签: javascript reactjs