簡體   English   中英

訪問React組件的道具

[英]Accessing React component's props

好的,所以我想修改ReactJS並編寫簡單的示例,一切工作都很好,我已經感覺到它提高了我的生產力。 現在,我正在研究一個簡單的React示例,該示例帶有一個應用名稱,並在檢測到Enter鍵時將其記錄到控制台。 一切正常,直到我在輸入框中輸入應用程序名稱並按Enter鍵,然后在控制台日志中看到的不是輸入值,而是“未定義”值。 這是完整的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")
);

你沒有把任何道具帶進去。 你會通過這樣的道具

實際上沒有在此應用程序中的任何地方傳遞道具:)

但是,您真正想要的是輸入框中的值。 因此,在React中您可以參考。 作為一個簡單而又骯臟的示例,我有一個全局上下文對象ctx={}

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

現在在我的組件中,我可以引用鍵入為

ctx._input.value

Console.log,它應該很好。

那是因為您沒有將值作為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

使用ref訪問輸入框的值

"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組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM