DOM 操作
React 组件中DOM 操作
React.findDOMNode()
方法能够帮我们根据refs
获取某个子组件的
var MyComponent = React.createClass({
handleClick: function() {
React.findDOMNode(this.refs.myTextInput).focus();
},
render: function() {
return (
<div>
<input type="text" ref="myTextInput" />
<input
type="button"
value="Focus the text input"
onClick={this.handleClick}
/>
</div>
);
}
});
React.render(<MyComponent />, document.getElementById("example"));
需要注意的是,由于
组件渲染到DOM
在源代码中,组件定义相关代码与渲染相关代码是相分离的。当我们声明了某个组件之后,可以通过ReactDOM
的render
函数将
const RootElement = (
<div>
<h1 style=>The world is yours</h1>
<p>Say hello to my little friend</p>
</div>
)
ReactDOM.render(RootElement, document.getElementById('app'))
Refs
整合非React 类库
jQuery Integration
目前,我们项目中不可避免的还会存在大量的基于
// JPlayer component
class JPlayer extends React.Component {
static propTypes = {
sources: React.PropTypes.array.isRequired
};
componentDidMount() {
$(this.refs.jplayer).jPlayer({
ready: () => {
$(this.refs.jplayer).jPlayer("setMedia", this.props.sources);
},
swfPath: "/js",
supplied: _.keys(this.props.sources)
});
}
componentWillUmount() {
// I don't know jPlayer API but if you need to destroy it do it here.
}
render() {
return <div ref="jplayer" className="jplayer" />;
}
}
// Use it in another component...
<JPlayer sources={{ m4a: "/media/mysound.mp4", oga: "/media/mysound.ogg" }} />;