可以使用jsx 方便组件的开发
基本格式
主要是render 函数
class MyComponent {
render() {
return (
<div>
<h1>Hello World</h1>
<p>This is JSX!</p>
</div>
);
}
}
数据绑定
render() {
return (
<div>Hello {this.name}</div>
)
}
条件语句
render() {
if (this.name) {
return ( <div>Hello {this.name}</div> )
} else {
return ( <div>Hello, World</div> )
}
}
slots
参考
render() {
return (
<div>
<h2>A Component</h2>
<div><slot /></div>
</div>
);
}
对于多个可以指定名称
参考
render(){
return [
<slot name="item-start" />,
<h1>Here is my main content</h1>,
<slot name="item-end" />
]
}
render(){
return(
<my-component>
<p slot="item-start">I'll be placed before the h1</p>
<p slot="item-end">I'll be placed after the h1</p>
</my-component>
)
}
loops 操作
参考
render() {
return (
<div>
{this.todos.map((todo) =>
<div>
<div>{todo.taskName}</div>
<div>{todo.isCompleted}</div>
</div>
)}
</div>
)
}
处理用户输入事件
使用原生dom 事件
参考
export class MyComponent {
handleClick(event: UIEvent) {
alert('Received the button click!');
}
render() {
return (
<button onClick={ (event: UIEvent) => this.handleClick(event)}>Click Me!</button>
);
}
}
获取dom 元素的引用
使用ref 进行参数绑定
参考
@Component({
tag: 'app-home',
})
export class AppHome{
textInput: HTMLInputElement;
handleSubmit = (ev: Event) => {
ev.preventDefault();
console.log(this.textInput.value);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={(el: HTMLInputElement) => this.textInput = el} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}