访问React组件的道具

时间:2016-06-22 16:30:57

标签: javascript reactjs

好吧,我正在修改ReactJS并处理简单的例子,一切都很好,我已经觉得它提高了我的工作效率。现在我正在研究一个简单的React示例,该示例采用应用程序名称并在检测到Enter键时将其记录到控制台。一切正常,直到我在输入框中输入应用程序名称并按Enter键,我在控制台日志中看到的不是输入值,而是" undefined"值。这是完整的JS代码:

"use strict";

var InputText = React.createClass({
    render() {
        return <div><p>Please input the app name you wish to access:</p></div>
    }
});

var InputBox = React.createClass({
    onKeyPress(e) {
      if (e.key === 'Enter') {
        console.log(this.props.value);
      }
    },
    render() {
        return <input type="text" onKeyPress={this.onKeyPress}></input>
    }
});

var AppForm = React.createClass({
    render() {
        return <div class="appForm">
            <InputText />
            <InputBox />
        </div>
    }
});

var App = React.createClass({
    render() {
        return <AppForm />
    }
});

ReactDOM.render(
    <App />,
    document.getElementById("container")
);

3 个答案:

答案 0 :(得分:1)

你没有通过任何道具。你会像这样传递道具

实际上在这个应用程序的任何地方都没有传递道具:)

但你真正想要的是输入框中的值。所以在React你会做一个参考。作为一个快速而肮脏的例子,我有一个全局上下文对象ctx={}

<input type="text" className="inputClass" style={inputStyles} ref={(c) => ctx._input = c} />

现在在我的组件中,我可以引用键入的值

ctx._input.value

Console.log那应该都很好。

答案 1 :(得分:1)

那是因为您没有将值作为prop传递给InputBox组件。

您可以从事件中获取值

var InputBox = React.createClass({
    onKeyPress(e) {
      if (e.key === 'Enter') {
        console.log('InputBox Value: ' + e.target.value);
      }
    },
    render() {
        return <input type="text" onKeyPress={this.onKeyPress}></input>
    }
});

jsfiddle

或者将值存储在状态中并从那里获取。

var InputBox = React.createClass({
    onKeyPress(e) {
      if (e.key === 'Enter') {
        console.log('InputBox Value: ' + this.state.value);
      }
    },
    render() {
        return <input type="text" onKeyPress={this.onKeyPress} onChange={(e) => this.setState({value: e.target.value})}></input>
    }
});

jsfiddle

答案 2 :(得分:1)

使用参考访问输入框的值

"use strict";

var InputText = React.createClass({
    render() {
        return <div><p>Please input the app name you wish to access:</p></div>
    }
});

var InputBox = React.createClass({
    onKeyPress(e) {
      if (e.key === 'Enter') {
        console.log(this.refs.textbox.value);
      }
    },
    render() {
        return <input type="text" onKeyPress={this.onKeyPress} ref = 'textbox'></input>
    }
});

var AppForm = React.createClass({
    render() {
        return <div class="appForm">
            <InputText />
            <InputBox />
        </div>
    }
});

var App = React.createClass({
    render() {
        return <AppForm />
    }
});

ReactDOM.render(
    <App />,
    document.getElementById("container")
);

<强> JSFIDDLE

获得价值的另一种方法是将事件 e 用作e.target.value。道具不起作用,因为你实际上并没有将道具传递给InputBox组件。

相关问题