如果我只是:
const App = function() {
return (
<div>{this.renderList()}</div>
)
}
Run Code Online (Sandbox Code Playgroud)
我该如何定义renderList方法?
我不能做const renderList = function() {}(也不能用var或let).我做不到renderList() {}.
什么是正确的语法?
Joh*_*ell 34
我对于解决这个问题犹豫不决,因为内联Stateless Functions不应该有方法.如果你想要一个方法你应该使用a Class并且使用类没有任何问题.一切都基于你需要做的事情.Stateless Functions被设计成一种超轻量级的方式来渲染不需要方法的东西,或者一个状态甚至是这个上下文(就类而言).
你应该这样做.
class App extends Component {
constructor(){
super();
// note this is a Stateless Component because its a react class without a state defined.
}
renderList = () => {
return <span>Something Here</span>;
}
render() {
return <div>{this.renderList()}</div>
}
}
Run Code Online (Sandbox Code Playgroud)
我不推荐的HACK方式(但确实以你想要的方式解决你的问题)就像这样.
const App = () => {
let renderList = () => {
return <span>Something Here</span>
}
return <div>{renderList()}</div>
}
Run Code Online (Sandbox Code Playgroud)
const App = function() {
const renderList = ()=> {
return "this variables"
}
return (
<div>{renderList()}</div>
)
}
Run Code Online (Sandbox Code Playgroud)
你会想做这样的事情
const App = function() {
return (
<div>{renderList()}</div>
)
}
function renderList(){
return "this variables"
}
Run Code Online (Sandbox Code Playgroud)
当然,这是一个不好的方法,建议您传入函数,因为 props 和无状态组件始终是愚蠢的组件。例如,如果您使用的是 redux,您可以让您的组件像这样渲染
import {connect} from 'react-redux';
const App = (props) => {
return (
<div> {props.renderList} </div>
)
}
function renderList (){
return "your render logic"
}
export default connect(null, {renderList})(App)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17807 次 |
| 最近记录: |