*如何定义组件
新建一个继承Component的组件,实现render方法
class CommentBox extends Component {
constructor(props) {
super(props);
this.state = {
title: 'hello'
};
}
render() {
return (
<View>
<Text> 评论列表 adddbc</Text>
</View>
);
}
}
- 如何组合组件
将CommentList组件以标签的方式嵌入到CommentBox组件中
class CommentBox extends Component {
constructor(props) {
super(props);
this.state = {
title: 'hello'
};
}
render() {
return (
<View style={styles.container}>
<Text> 评论列表 adddbc</Text>
<CommentList msg= {this.state.title} />
</View>
);
}
}
- 父组件向子组件传值
父组件在子组件的标签上设置标签值
<Comment author = "小明" />
子组件中通过this.props.fileName获取值
<Text> {this.props.author} </Text>
//父组件
class CommentList extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<View>
<Comment content = "天气不错啊" author = "小雪" data = "6分钟前" />
<Comment content = "出去玩啊" author = "小明" data = "3分钟前" />
</View>
);
}
}
//子组件
class Comment extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<View >
<Text> {this.props.author} {this.props.data}</Text>
<Text> {this.props.content} </Text>
</View>
);
}
}
- 访问页面上显示的元素 - refs
例如用户提交表达的时候,要得到表单上面各项输入的内容
在标签上定义ref,使用的时候用this.refs.refName.value
//定义ref
<TextInput ref='author' placeholder='姓名'></TextInput>
//使用ref
let author = this.refs.author.value;
- 子组件传递数据给父组件
在父组件定义一个方法handleCommentSubmit用于提供给子组件调用, 在组件标签定义
<CommentFrom onCommentSubmit={this.handleCommentSubmit.bind(this)}/>
在子组件调用this.props.onCommentSubmit()就可以调用到父组件的这个方法了
class CommentBox extends Component {
handleCommentSubmit(comment){
console.log('handleCommentSubmit '+JSON.stringify(comment));
let comments = this.state.data;
let newComment = comments.concat(comment);
this.setState({
data:newComment,
});
}
render() {
console.log("CommentBox render");
return (
<View style={{margin:20}}>
<CommentList data={this.state.data} />
{/* 因为handleCommentSubmit方法中有用到this.setState,所以这里需要绑定下 */}
<CommentFrom onCommentSubmit={this.handleCommentSubmit.bind(this)}/>
</View>
);
}
}
export default class CommentFrom extends Component {
render() {
return (
<View>
<TextInput
placeholder="姓名"
onChangeText={text => {
this.setState({
name: text
});
}}
/>
<TextInput
placeholder="评论"
onChangeText={text => {
this.setState({
content: text
});
}}
/>
<Button title="提交" onPress={this.handleSubmit.bind(this)} />
</View>
);
}
}
handleSubmit() {
let author = this.state.name;
let content = this.state.content;
let data = '刚刚';
this.props.onCommentSubmit({author,content,data});
}
网友评论