[英]Can we pass more than one props from a stateless component and get it as single arguments in another stateless component in react?
I am trying to pass more than one props to a functional component and getting in the component as single argument props but getting error in InputBox component at placeholder as item is undefined 我试图将多个道具传递给功能组件,并将该组件作为单参数道具进入,但是由于未定义项,在占位符的InputBox组件中出现错误
export default ({change, state}) => (
<div style={styles.container}>
<h3 style={{margin: 0, marginBottom: 15}}>InputData</h3>
{items.map((item) => (
<div style={styles.lineContainer}>
{(() => {
switch(item.name) {
case "name1": return <InputBox handleChange ={change} state ={state} item={item}/>
case "name2": return <SelectBox handleChange ={change} state ={state} item={item}/>;
case "name3": return <SelectBox handleChange ={change} state ={state} item={item}/>;
default: return <InputBox/>
}
})()}
</div>
))}
</div>
);
const InputBox = props =>
<input
type="text"
placeholder={props.item.place}
name={props.item.name}
value={props.state[props.item.name]}
onChange={props.change}
required
style={{height: 20}}
/>
There are more than one problems with your code. 您的代码有多个问题。
in your first component, where the line is items.map((item)=>....
, items
is not defined anywhere. Assumption: maybe you had to destructure it from state or get another prop. 在您的第一个组件中,该行是items.map((item)=>....
, items
并没有在任何地方定义假设:也许您必须将其从状态中items.map((item)=>....
或获取另一个道具。
Your component InputBox
is expecting some props, ie, in const InputBox = props =>...
. 您的组件InputBox
需要一些道具,即const InputBox = props =>...
And these props are not being passed from default: return <InputBox/>
, just like you did in case "name1"
. 而且这些道具不是default: return <InputBox/>
传递的default: return <InputBox/>
,就像在case "name1"
一样。
PS, you can define default props if you don't have any intentions of sending props to <InputBox />
. PS,如果您不打算将道具发送到<InputBox />
,则可以定义默认道具。
As I can make out, this is happening because for default case in switch you are returning <InputBox/>
without any props but inside your InputBox
component you are trying to refer to a prop using props.item.place. 可以看出来,这是因为在switch的默认情况下,您返回的<InputBox/>
没有任何道具,但是在InputBox
组件内部,您试图使用props.item.place引用道具。 Hence this error. 因此,此错误。
Either make sure that switch returns appropriate value for default case or configure component to adjust to props. 确保开关为默认情况返回适当的值,或者将组件配置为调整为道具。
I don't see any items
array in your default export. 我没有在默认导出中看到任何items
数组。 I think you forgot to destruct
it from your state
. 我认为您忘记了将其从您的state
destruct
。
Use state.items.map(...)
instead of items.map(...)
in your default export. 在默认导出中使用state.items.map(...)
而不是items.map(...)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.