我目前正在嘗試使用表示和容器組件重構流星的簡單教程教程,但遇到了試圖訪問功能無狀態組件中的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
時,我應該放棄使用無狀態的功能組件?
'handleSubmit'定義在哪裏?'ref'只能從有狀態組件中訪問。 –
你不能像這樣使用裁判。你在一個單獨的組件裏面做'this.ref',其中textInput不存在。 – jzm