我有以下代码
class Iframe extends Component {
constructor (props) {
super()
this.state = {
iFrameHeight: '0px',
}
this.iFrameUrl = props.url
}我想要访问渲染函数中的属性,如下所示:
render (props) {
return (
<iframe
style={{width: '100%', height: this.state.iFrameHeight, overflow: 'visible'}}
onLoad={() => {
const obj = ReactDOM.findDOMNode(this)
this.setState({
'iFrameHeight': obj.contentWindow.document.body.scrollHeight + 'px'
})
}}
ref='iframe'
src={props.url}
width='100%'
scrolling='no'
frameBorder='0'
sandbox='allow-same-origin allow-scripts'
/>
)
}我正在从道具中获取iframe的src URL。在render的返回方法中访问props的正确方式是什么?
发布于 2018-10-25 01:09:31
如果您在构造函数中接受props,则还需要将其传递给父组件。(在本例中为React.Component)
class Iframe extends Component {
constructor (props) {
super(props);
...
}一旦准备就绪,您就可以随时在任何组件函数/生命周期挂钩/呈现方法中引用props,只需简单地使用
this.props.url //any key in your prop
所以现在,在构造函数中使用this.props.url
constructor (props) {
super(props);
this.state = {
iFrameHeight: '0px',
}
this.iFrameUrl = this.props.url
}如果你想修改url,那么在render方法中使用this.frameUrl,否则你可以在render方法中直接使用this.props.url。
发布于 2018-10-25 00:53:48
您只需使用this.props,如果您想在JSX中使用它,请确保用大括号将其括起来。
render () {
console.log(this.props) // this is how to use props inside render method
return (
<iframe
style={{width: '100%', height: this.state.iFrameHeight, overflow: 'visible'}}
onLoad={() => {
const obj = ReactDOM.findDOMNode(this)
this.setState({
'iFrameHeight': obj.contentWindow.document.body.scrollHeight + 'px'
})
}}
ref='iframe'
src={props.url}
width='100%'
scrolling='no'
frameBorder='0'
sandbox='allow-same-origin allow-scripts'
/>
)
}https://stackoverflow.com/questions/52974146
复制相似问题