2016-07-22 68 views
0

我目前正在嘗試使用表示和容器組件重構流星的簡單教程教程,但遇到了試圖訪問功能無狀態組件中的input的引用的問題。我發現要訪問refs,你必須將組件包裝在一個有狀態的組件中,我使用input訪問有狀態組件中的ref在React中不起作用?

// import React ... 
import Input from './Input.jsx'; 

const AppWrapper = (props) => { 
    // ... more lines of code 

    <form className="new-task" onSubmit={props.handleSubmit}> 
    <Input /> 
    </form> 
} 

import React, { Component } from 'react'; 

此輸入應該是有狀態的,因爲它使用類語法,至少我認爲。

export default class Input extends Component { 

    render() { 
    return (
     <input 
     type="text" 
     ref="textInput" 
     placeholder="Type here to add more todos" 
     /> 
    ) 
    } 
} 

我用裁判的涵蓋AppContainer搜索輸入的值。

import AppWrapper from '../ui/AppWrapper.js'; 

handleSubmit = (event) => { 
    event.preventDefault(); 
    // find the text field via the React ref 
    console.log(ReactDOM.findDOMNode(this.refs.textInput)); 
    const text = ReactDOM.findDOMNode(this.refs.textInput).value.trim(); 
    ... 
} 

中的console.log的結果是null,所以我輸入組件無狀態的?我是否需要設置一個構造函數來爲this.state設置一個值來使這個組件成爲有狀態的,或者當我需要使用refs時,我應該放棄使用無狀態的功能組件?

+0

'handleSubmit'定義在哪裏?'ref'只能從有狀態組件中訪問。 –

+0

你不能像這樣使用裁判。你在一個單獨的組件裏面做'this.ref',其中textInput不存在。 – jzm

回答

0

或者我應該放棄在我需要使用refs時使用功能無狀態組件?

是的。如果組件需要保持對它們呈現的元素的引用,則它們是有狀態的。

參考文獻可以像這樣一個「回調」功能進行設置:

export default class Input extends Component { 

    render() { 
    // the ref is now accessable as this.textInput 
    alert(this.textInput.value) 
    return ( 
     <input 
     type="text" 
     ref={node => this.textInput = node} 
     placeholder="Type here to add more todos" 
     /> 
    ) 
    } 
} 
0

你必須使用裁判時使用狀態的組件。在你的handleSubmit事件中,當字段位於單獨的組件中時,你調用'this.refs'。

要使用refs,您需要將ref添加到您呈現AppWrapper的位置,並且AppWrapper本身必須是有狀態的。

下面是一個例子:

AppWrapper - 這是你的形式

class AppWrapper extends React.Component { 
    render() { 
    return (
     <form 
     ref={f => this._form = f} 
     onSubmit={this.props.handleSubmit}> 
     <Input 
      name="textInput" 
      placeholder="Type here to add more todos" /> 
     </form> 
    ); 
    } 
}; 

輸入 - 這是一種可重複使用的文本框組件

const Input = (props) => (
    <input 
    type="text" 
    name={props.name} 
    className="textbox" 
    placeholder={props.placeholder} 
    /> 
); 

應用 - 這是容器組件

class App extends React.Component { 
    constructor() { 
    super(); 
    this.handleSubmit = this.handleSubmit.bind(this); 
    } 

    handleSubmit(event) { 
    event.preventDefault(); 
    const text = this._wrapperComponent._form.textInput.value; 
    console.log(text); 
    } 

    render() { 
    return (
     <AppWrapper 
     handleSubmit={this.handleSubmit} 
     ref={r => this._wrapperComponent = r} 
     /> 
    ); 
    } 
} 

http://codepen.io/jzmmm/pen/BzAqbk?editors=0011

正如你看到的,輸入組件是無狀態的,並且AppWrapper是有狀態的。您現在可以避免使用ReactDOM.findDOMNode,並直接訪問textInput。輸入必須具有要引用的name屬性。

您可以通過將<form>標記移動到App組件中來簡化此操作。這將消除一個ref

相關問題