Shallow render a functional stateless component -react
我在React中有一个功能组件,定义如下
1 2 3 4 5 6 7 8 9 | const MyComponent = ({ prop1, prop2, prop3 }, param1 , param2) => { return [ //list of spans ] } |
在spec文件中,我使用了浅浅的颜色来渲染组件
1 2 3 4 5 6 7 | const fakeObj = { prop1:value, prop2:value, prop3:value } shallow(<MyComponent {...fakeObj} param1={something} param2={something} />) |
但是,当我在MyComponent中进行console.log的参数设置时,分别为{{}和undefined分别指定了param1和param2,同时获得了fakeObj。参数之一?
当我只是从规格文件中调用组件作为函数时,即
1 | MyComponent({fakObj},param1,param2) |
,我获得了正确的params值,但无法使用酶正确找到span元素。
反应功能组件,也许功能(创建组件的功能)仅接受一个参数来获取其道具。因此,您不能以所做的方式(定义多个参数)定义功能组件。您必须像下面这样定义它。
1 2 3 4 5 6 7 8 | let MyComponent = (props) => { // props is an object, it contains all props passed by component call. // So you can get property value as props.propName return 'something' // what you like to return. } |
如果使用像bellow
这样的组件
1 | <MyComponent prop1="Propone 1 Value" prop2="Prop 2 Value" prop3="Prop 3 Value" /> |
组件内部的控制台道具,例如
1 2 3 4 | let MyComponent = (props) => { console.log(props); return 'something' // what you like to return. } |
您将获得所有传递的属性作为函数自变量(作为props参数),作为一个对象,如下所示。
1 2 3 4 5 | { prop1:"Propone 1 Value", prop2:"Propone 2 Value", prop3:"Propone 3 Value" } |
现在满足您的要求。您可以像以下
一样创建组件
1 2 3 4 5 6 7 8 | let Home = (props) => { let {fakeObj, param1, param2} = props; return [ //list of spans ] } |
然后调用这样的组件
1 2 3 4 5 6 7 | const fakeObj = { prop1:value, prop2:value, prop3:value } shallow(<MyComponent fakeObj = {fakeObj} param1={something} param2={something} />) |