gpt4 book ai didi

javascript - react : How to supply callback arrow functions to stateless functional child components?

转载 作者:行者123 更新时间:2023-11-30 11:33:05 27 4
gpt4 key购买 nike

我正在努力为无状态功能子组件提供回调函数。我有这两个组件:

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&uuml;rzel eingeben"
onChange={callback}/>
</FormGroup>
</form>
</Col>);
};

在渲染过程中出现以下错误:

Warning: Failed form propType: Invalid prop onChange of type object supplied to input, expected function. Check the render method of FormControl.

每次我在文本输入中输入内容时,都会出现以下错误:

Uncaught TypeError: inputProps.onChange.call is not a function at Object.executeOnChange (LinkedValueUtils.js:132)

这在无状态环境中完全可能吗?从技术上讲,提供的回调函数是常量,因此 CommandInput 组件中没有固有状态。我已经看到一些答案将绑定(bind)函数弄乱到正确的 this 指针,但我想尽可能避免这种情况。

最佳答案

您的 SFC 接收的单个参数是一个属性对象,该对象具有 JSX 标记中组件上使用的每个属性的属性。

因此要么接受该属性并使用其回调属性:

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>

关于javascript - react : How to supply callback arrow functions to stateless functional child components?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45548803/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com