React+AntD的使用记录
1、超链接的跳转禁用以及颜色的调整
<a
style={{pointerEvents:this.state.data==undefined?"none":"",
this.state.data==undefined?"#666666":""}}
href="javascript:;"
onClick={() => this.view()}>{}
</a>
2、React子组件向父组件返回一些数据
2.1、子组件主动传递一定的数据到父组件
父组件:(这里使用了antD的模态框)
<Modal
title='模态框'
visible={this.state.visible}
onOk={this.oK}
onCancel={this.cancel}
okText={'确定'}
cancelText={'取消'}
destroyOnClose={true}
maskClosable={false}
width={750}>
<SubComponent setXXX={(info) => {this.state.xxx= info;}} </SubComponent >
</Modal>
子组件:
let info = {};
//...
this.props.setXXX(info);
这样就可以在父组件中使用this.state.xxx
获取到子组件传递过来的消息了。
2.2、将子组件部分或者全部绑定为父组件的一个新属性
父组件:(这里使用了antD的模态框)
<Modal
title='模态框'
visible={this.state.visible}
onOk={this.oK}
onCancel={this.cancel}
okText={'确定'}
cancelText={'取消'}
destroyOnClose={true}
maskClosable={false}
width={750}>
<SubComponent onRef={this.onRef}> </SubComponent >
</Modal>
//onRef函数
onRef = (ref)=>{
// 绑定子组件调用时传递的参数
this.child = ref;
}
子组件:
//子组件在加载完成后就把·自己·绑定到父组件中,这样子组件只需要把要
//传递的数据,放在自身就ok,父组件可以去主动获取子组件的任何的数据。
componentDidMount() {
this.props.onRef(this);
}
在父组件的child
的属性下就是整个子组件。
3、确保React数据异步加载的顺序
在使用react时由于组件和ajax异步请求数据时,在需要有加载先后顺序的数据时有可能会获取不到改数据,说明此时该数据还没未返回,可以粗浅的使用以下的办法临时解决一下:
request('get', url,{params})
.then(res=>{
//...
//setState添加callback函数,在次函数中调用下一步该执行的js
this.setState({},()=>{})
})
.catch(err=>{
//...
})
4、this.props.form.getFieldDecorator(id, options)
经过 getFieldDecorator
包装的控件,表单控件会自动添加value
(或 valuePropName
指定的其他属性)onChange
(或 trigger
指定的其他属性),数据同步将被 Form
接管,这会导致以下结果:
1、你不再需要也不应该用 onChange
来做同步,但还是可以继续监听 onChange
等事件。
2、你不能用控件的 value
、 defaultValue
等属性来设置表单域的值,默认值可以用 getFieldDecorator
里的 initialValue
。
3、你不应该用 setState
,可以使用this.props.form.setFieldsValue
来动态改变表单值。
原文:https://blog.csdn.net/weixin_44874595/article/details/104268036
5、在Modal中有时会缺失form属性导致无法使用getFieldDecorator
在Modal
的子组件中中有时会缺失form
属性,导致在render
函数中
const { getFieldDecorator } = this.props.form;
报错。
解决办法:
class Form extends Component {
//...
}
const addForm= Form.create()(Form);
export default addForm;
可能是因为缺失const addForm= Form.create()(Form);
导致的,加上即可。
这样就可以在子组件中使用const { getFieldDecorator } = this.props.form;
进行表单的相关操作了。