[英]React: How to supply callback arrow functions to stateless functional child components?
我正在努力為無狀態功能子組件提供回調函數。 我有這兩個組成部分:
export const FrontDeskGUI = () => {
const callback = (event) => console.log(event.target.value);
return (
<Col xs={12}>
<Panel collapsible defaultExpanded header="Empfang">
<ButtonGrid/>
</Panel>
<Panel collapsible defaultExpanded header="Verwaltung">
<ButtonGrid/>
</Panel>
<CommandInput callback={callback}/>
</Col>);
};
export const CommandInput = (callback) => {
const style = {
textTransform: 'uppercase'
};
return (
<Col xs={12}>
<form>
<FormGroup
controlId="command">
<FormControl
type="text"
style={style}
placeholder="Kürzel eingeben"
onChange={callback}/>
</FormGroup>
</form>
</Col>);
};
在渲染過程中,我收到以下錯誤:
警告:無法形式propType:無效支柱
onChange
類型的object
提供給input
,預期function
。 檢查FormControl
的render方法。
每次我在文本輸入中輸入內容時,都會出現以下錯誤:
未捕獲的TypeError:inputProps.onChange.call不是Object.executeOnChange中的函數(LinkedValueUtils.js:132)
這在無狀態環境中是否可行? 從技術上講,提供的回調函數是常量,因此CommandInput組件中沒有固有狀態。 我已經看到一些答案亂用綁定函數到正確的指針,但我想盡可能避免這種情況。
SFC接收的單個參數是一個屬性對象,其中包含JSX標記中組件上使用的每個屬性的屬性。
因此要么接受屬性並使用其callback
屬性:
export const CommandInput = (props) => {
// ...use props.callback...
}
或使用參數解構:
export const CommandInput = ({callback}) => {
// ^--------^---------------- note { }
// ... use callback...
}
目前,您正在嘗試將props對象本身用作onChange
,這就是您收到錯誤的原因。
使用解構的示例:
const Example = ({callback}) => <div onClick={callback}>Click me</div>; ReactDOM.render( <Example callback={() => console.log("Clicked")} />, document.getElementById("root") );
<div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.